Java压缩文件/目录成ZIP包最新技巧
时间:2010-05-31
使用java自带的类java.util.zip进行文件/目录的压缩的话,有一点不足,不支持中文的名件/目录命名,如果有中文名,那么打包就会失败。本人经过一段时间的摸索和实践,发现在一般的Ant.jar类库中也有zip类,import org.apache.tools.zip.*,能够解决不支持中文文件目录的问题,同时,Ant的获得途径也比较多,一般的应用服务器中有这个包,实在不行去下载个tomcat5.X,里面也有ant.jar,本人经过测试,可以使用。
例子如下:
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:\\test.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工具打成的包,和大家分享一下! |