使用java自帶的類 java.util.zip進行文件/目錄的壓縮的話,有一點不足,不支持中文的名件/目錄命名,如果有中文名,那么打包就會失敗。本人經(jīng)過一段時間的摸索和實踐,發(fā)現(xiàn)在一般的Ant.jar類庫中也有zip類,import org.apache.tools.zip.*,能夠解決不支持中文文件目錄的問題,同時,Ant的獲得途徑也比較多,一般的應用服務器中有這個包,實在不行去下載個tomcat5.X,里面也有ant.jar,本人經(jīng)過測試,可以使用。
例子如下:
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工具打成的包,和大家分享一下!
(責任編輯:代碼如詩) |