| 12 | |
| 13 | public class ZipCompress { |
| 14 | public static void main(String[] args) { |
| 15 | try( |
| 16 | FileOutputStream f = |
| 17 | new FileOutputStream("test.zip"); |
| 18 | CheckedOutputStream csum = |
| 19 | new CheckedOutputStream(f, new Adler32()); |
| 20 | ZipOutputStream zos = new ZipOutputStream(csum); |
| 21 | BufferedOutputStream out = |
| 22 | new BufferedOutputStream(zos) |
| 23 | ) { |
| 24 | zos.setComment("A test of Java Zipping"); |
| 25 | // No corresponding getComment(), though. |
| 26 | for(String arg : args) { |
| 27 | System.out.println("Writing file " + arg); |
| 28 | try( |
| 29 | InputStream in = new BufferedInputStream( |
| 30 | new FileInputStream(arg)) |
| 31 | ) { |
| 32 | zos.putNextEntry(new ZipEntry(arg)); |
| 33 | int c; |
| 34 | while((c = in.read()) != -1) |
| 35 | out.write(c); |
| 36 | } |
| 37 | out.flush(); |
| 38 | } |
| 39 | // Checksum valid only after the file is closed! |
| 40 | System.out.println( |
| 41 | "Checksum: " + csum.getChecksum().getValue()); |
| 42 | } catch(IOException e) { |
| 43 | throw new RuntimeException(e); |
| 44 | } |
| 45 | // Now extract the files: |
| 46 | System.out.println("Reading file"); |
| 47 | try( |
| 48 | FileInputStream fi = |
| 49 | new FileInputStream("test.zip"); |
| 50 | CheckedInputStream csumi = |
| 51 | new CheckedInputStream(fi, new Adler32()); |
| 52 | ZipInputStream in2 = new ZipInputStream(csumi); |
| 53 | BufferedInputStream bis = |
| 54 | new BufferedInputStream(in2) |
| 55 | ) { |
| 56 | ZipEntry ze; |
| 57 | while((ze = in2.getNextEntry()) != null) { |
| 58 | System.out.println("Reading file " + ze); |
| 59 | int x; |
| 60 | while((x = bis.read()) != -1) |
| 61 | System.out.write(x); |
| 62 | } |
| 63 | if(args.length == 1) |
| 64 | System.out.println( |
| 65 | "Checksum: "+csumi.getChecksum().getValue()); |
| 66 | } catch(IOException e) { |
| 67 | throw new RuntimeException(e); |
| 68 | } |
| 69 | // Alternative way to open and read Zip files: |
| 70 | try( |
| 71 | ZipFile zf = new ZipFile("test.zip") |