java压缩文件目录 为 zip

来源:互联网 发布:matlab二维数组 编辑:程序博客网 时间:2024/05/01 03:04

import org.apache.tools.zip.ZipOutputStream;

out 输出的zip文件流

f  要压缩的文件夹

base 压缩在zip流中文件的根目录

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();
       }
    }
0 0
原创粉丝点击