这篇文章将为大家详细讲解有关java如何实现文件夹解压和压缩,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
效果
实现多个文件以及文件夹的压缩和解压
代码分析
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class Main {
public static void main(String[] args) throws IOException {
//解决中文乱码
//压缩 参数改成你自己的源文件路径和压缩后的文件路径
//yasuo("C:\\file\\", "C:\\file.zip");
//解压 参数改成你自己的源文件路径和解压后的文件路径
jieya("C:\\file.zip", "C:\\file\\");
}
public static void jieya(String zipPath, String path) throws IOException, FileNotFoundException {
//创建解压后的文件夹
File pt=new File(path.substring(0,path.length()-1));
if(!pt.exists()) {
pt.mkdirs();
}
//try(resource)来保证InputStream正确关闭
try(ZipInputStream zip=new ZipInputStream(new FileInputStream(zipPath))){
//ZipEntry表示一个压缩文件或目录
ZipEntry entry;
while((entry=zip.getNextEntry())!=null) {
String name=entry.getName();
//压缩文件
if(!(entry.getName().contains(File.separator))) {
FileOutputStream file= new FileOutputStream( path+ name);
int n=0;
while((n=zip.read())!=-1) {
file.write(n);
}
}else {
//目录
int index=name.lastIndexOf("\\");
File file= new File(path+ name.substring(0,index));
if(!file.exists()) {
file.mkdirs();
}
//如果不是空目录
if(index!=name.length()-1) {
FileOutputStream f= new FileOutputStream( path+ name);
int n=0;
while((n=zip.read())!=-1) {
f.write(n);
}
}
}
}
zip.closeEntry();
}
}
public static void yasuo(String path, String zipPath) throws IOException, FileNotFoundException {
File zp=new File(zipPath);
if(!zp.exists()) {
zp.createNewFile();
}
try(ZipOutputStream zip=new ZipOutputStream(new FileOutputStream(zp))) {
File files= new File(path);
File[] f=files.listFiles();
for (File file : f) {
zipAll(zip, file,file.getName());
}
}
}
public static void zipAll(ZipOutputStream zip, File files,String name) throws IOException, FileNotFoundException {
if(files.isDirectory()) {
File[] files2=files.listFiles();
if(files2.length==0||files2==null) {
zip.putNextEntry(new ZipEntry(name+File.separator));
}else{
for (File file2 : files2) {
if(file2.isFile()) {
zip.putNextEntry(new ZipEntry(name+File.separator+file2.getName()));
int n;
FileInputStream input=new FileInputStream(file2);
while((n=input.read())!=-1) {
zip.write(n);
}
}
else {
zipAll(zip,file2,name+File.separator+file2.getName());
}
}
}
}else {
zip.putNextEntry(new ZipEntry(name));
int n;
FileInputStream input=new FileInputStream(files);
while ((n=input.read())!=-1) {
zip.write(n);
}
}
}
}
关于“java如何实现文件夹解压和压缩”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。