package test; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.zip.Adler32; import java.util.zip.CheckedInputStream; import java.util.zip.CheckedOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; public class ZipCompress { private static final String FILE_PREFIX_PATH = "E:\\\\gittest\\"; private static final String FILE_TARGET_PATH = "E:\\\\gittest\\Test.zip"; private static List<String> fileList = new ArrayList<String>() { { add("Test1.txt"); add("Test2.txt"); add("Test3.txt"); } }; public static void main(String[] args) { try { FileOutputStream f = new FileOutputStream(FILE_TARGET_PATH); CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32()); ZipOutputStream zos = new ZipOutputStream(csum); BufferedOutputStream out = new BufferedOutputStream(zos); zos.setComment("A test of java Zipping"); // No corresponding getComment(), though. for (String item : fileList) { System.out.println("Writing file: " + item); BufferedReader in = new BufferedReader(new FileReader(FILE_PREFIX_PATH + item)); zos.putNextEntry(new ZipEntry(item)); int c; while ((c = in.read()) != -1) { out.write(c); } in.close(); out.flush(); } out.close(); // Checksum valid only after the file has been closed! System.out.println("Checksum: " + csum.getChecksum().getValue()); // Now extract the files - Example1: System.out.println("========================Reading File - Example 1================================"); CheckedInputStream csum2 = new CheckedInputStream(new FileInputStream(FILE_TARGET_PATH), new Adler32()); ZipInputStream in2 = new ZipInputStream(csum2); BufferedInputStream bi2 = new BufferedInputStream(in2); ZipEntry ze; while ((ze = in2.getNextEntry()) != null) { System.out.println("Reading file: " + ze); int x; while ((x = bi2.read()) != -1) { System.out.write(x); } // Line feed System.out.println(); } if (fileList.size() == 1) { System.out.println("Checksum: " + csum.getChecksum().getValue()); } bi2.close(); // Now extract the files - Example2: System.out.println("========================Reading File - Example 2================================"); ZipFile zf = new ZipFile(FILE_TARGET_PATH); Enumeration e = zf.entries(); while (e.hasMoreElements()) { ZipEntry ze2 = (ZipEntry) e.nextElement(); System.out.println("File: " + ze2); BufferedInputStream bi3 = new BufferedInputStream(zf.getInputStream(ze2)); int x; while ((x = bi3.read()) != -1) { System.out.write(x); } // Line feed System.out.println(); bi3.close(); } if (fileList.size() == 1) { System.out.println("Checksum: " + csum.getChecksum().getValue()); } } catch (IOException e) { throw new RuntimeException(e); } } }
运行: