Java压缩文件/目录成ZIP包最新技巧
岁数大了,QQ也不闪了,微信也不响了,电话也不来了,但是图老师依旧坚持为大家推荐最精彩的内容,下面为大家精心准备的Java压缩文件/目录成ZIP包最新技巧,希望大家看完后能赶快学习起来。
例子如下:
import java.io.File;
import org.apache.tools.zip.ZipOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import dianda.cwmanage.*;
import dianda.com.util.Format;
public class CompressBook {
public CompressBook() {
}
public void zip(String inputFileName) throws Exception {
String zipFileName="c:est.zip";//打包后文件名字
System.out.println(zipFileName);
zip(zipFileName, new File(inputFileName));
}
private void zip(String zipFileName, File inputFile) throws Exception {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
zip(out, inputFile, "");
System.out.println("zip done");
out.close();
}
private void zip(ZipOutputStream out, File f, String base) throws Exception {
if (f.isDirectory()) {
File[] fl = f.listFiles();
out.putNextEntry(new org.apache.tools.zip.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 org.apache.tools.zip.ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
System.out.println(base);
while ( (b = in.read()) != -1) {
out.write(b);
}
in.close();
}
}
}
唯一遗憾,美中不足的是,无论,java.util.zip或者org.apache.tools.zip都不能解压rar工具打成的rar包,搜了半天也找不到采用java解压rar工具打成的包,盼望哪位高人能够提供解压rar工具打成的包,和大家分享一下!进入讨论组讨论。