上次写的貌似只能压缩文件,不能压缩文件夹,后来发现有了这个需求后,就又优化了一下。如下所示
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
public class Demo {
public static void main(String args[]){
String filePath="F:/test/default/dd.zip";
String descDir="f://demo";
Demo d=new Demo();
try {
d.zip(descDir,filePath);
} catch (Exception e) {
e.printStackTrace();
}
}
public String zip(String sourceFilePath,String zipFilePath) {
File inputFile=new File(sourceFilePath);
File zipFile=new File(zipFilePath);
String zipName=zipFile.getName();
//当传进的压缩路径是目录时,默认压缩后的文件名为要压缩的文件/文件夹名
if(zipFile.isDirectory()){
zipName="/"+inputFile.getName()+".zip";
zipFilePath+=zipName;
}
ZipOutputStream out;
try {
out = new ZipOutputStream(new FileOutputStream(zipFilePath));
zip(out, inputFile, inputFile.getName());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
return zipName;
}
private void zip(ZipOutputStream out, File f, String base) throws Exception {
if (f.isDirectory()) {
File[] fl = f.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + fl[i].getName());
}
}else {
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
System.out.println(base);
while ( (b = in.read()) != -1) {
out.write(b);
}
in.close();
}
}
}