技巧:使用Java把文件/目录压缩成ZIP包
来源:岁月联盟
时间:2007-07-10
使用java自带的类 java.util.zip进行文件/目录的压缩的话,有一点不足,不支持中文的文件/目录命名,如果有中文名,那么打包就会失败。在Ant.jar类库中也有zip类,引入 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;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(); } }}