package com.zjw; import java.util.zip.*; import java.io.*; public class MyZip { private void zip(String zipFileName, File inputFile) throws IOException { ZipOutputStream out = new ZipOutputStream(new FileOutputStream( zipFileName)); // 创建ZipOutputStream类对象 zip(out, inputFile, "");// 调用方法 System.out.println("压缩中..."); out.close();// 将流关闭 } private void zip(ZipOutputStream out, File f, String base) throws IOException { if (f.isDirectory()) {// 测试此抽象路径名表示的文件是否是一个目录 File[] fl = f.listFiles(); // 获取路径数组 for (int i = 0; i < fl.length; i++) { System.out.println(fl[i].getName() + " " + fl[i].getPath());// 输出路径数组 } System.out.println(); out.putNextEntry(new ZipEntry(base + "/"));// 写入此目录的Entry base = base.length() == 0 ? "" : base + "/";// 判断参数是否为空 for (int i = 0; i < fl.length; i++) {// 循环遍历数组中的文件 zip(out, fl[i], fl[i].getPath()); } } else { out.putNextEntry(new ZipEntry(base));// 创建新的进入点 FileInputStream in = new FileInputStream(f); int b; System.out.println(base); while ((b = in.read()) != -1) { out.write(b);// 将字节写入当前ZIP条目 } in.close(); } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub MyZip book = new MyZip();// 创建本例对象 try { book.zip("hello.zip", new File("src")); // 调用方法,参数为压缩后的文件与要压缩的文件 System.out.println("压缩完成"); } catch (Exception e) { e.printStackTrace(); } } } 输出结果如下: com src\com zjw src\com\zjw MyZip.java src\com\zjw\MyZip.java src\com\zjw\MyZip.java 压缩中... 压缩完成 out.putNextEntry(new ZipEntry(base + "/"));// 写入此目录的Entry base = base.length() == 0 ? "" : base + "/";// 判断参数是否为空 这两句话有什么用?为什么要将字节写入ZIP条目? 还有为什么我得到的压缩文件中会有hello这个文件夹?求详细解释
2012-11-30 15:17
提问者采纳
out.putNextEntry(new ZipEntry(base + "/"));// 写入此目录的Entry 这句应该是将文件压入zip文件的根目录下 base = base.length() == 0 ? "" : base + "/";// 判断参数是否为空 这句子是判断写入压缩文件的目录,默认写入压缩文件的根目录 有hello这个文件夹应该是你src中有这个文件吧
-
提问者评价
-
谢谢!