OnJava8-Examples/compression/ZipCompress.java

69 lines
2.3 KiB
Java
Raw Normal View History

2015-11-03 12:00:44 -08:00
// compression/ZipCompress.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -07:00
// Uses Zip compression to compress any
// number of files given on the command line.
// {Args: ZipCompress.java}
import java.util.zip.*;
import java.io.*;
import java.util.*;
public class ZipCompress {
public static void main(String[] args)
throws IOException {
2015-12-15 11:47:04 -08:00
try(FileOutputStream f = new FileOutputStream("test.zip");
CheckedOutputStream csum =
new CheckedOutputStream(f, new Adler32());
ZipOutputStream zos = new ZipOutputStream(csum);
BufferedOutputStream out =
new BufferedOutputStream(zos)) {
2015-06-15 17:47:35 -07:00
zos.setComment("A test of Java Zipping");
// No corresponding getComment(), though.
for(String arg : args) {
2015-11-03 12:00:44 -08:00
System.out.println("Writing file " + arg);
2015-06-15 17:47:35 -07:00
try(InputStream in = new BufferedInputStream(
new FileInputStream(arg))) {
zos.putNextEntry(new ZipEntry(arg));
int c;
while((c = in.read()) != -1)
out.write(c);
}
out.flush();
}
2015-12-15 11:47:04 -08:00
// Checksum valid only after the file is closed!
System.out.println(
"Checksum: " + csum.getChecksum().getValue());
2015-06-15 17:47:35 -07:00
}
// Now extract the files:
2015-11-03 12:00:44 -08:00
System.out.println("Reading file");
2015-12-15 11:47:04 -08:00
try(FileInputStream fi = new FileInputStream("test.zip");
CheckedInputStream csumi =
new CheckedInputStream(fi, new Adler32());
ZipInputStream in2 = new ZipInputStream(csumi);
BufferedInputStream bis =
new BufferedInputStream(in2)) {
2015-06-15 17:47:35 -07:00
ZipEntry ze;
while((ze = in2.getNextEntry()) != null) {
2015-11-03 12:00:44 -08:00
System.out.println("Reading file " + ze);
2015-06-15 17:47:35 -07:00
int x;
while((x = bis.read()) != -1)
System.out.write(x);
}
if(args.length == 1)
2015-12-02 09:20:27 -08:00
System.out.println(
"Checksum: "+csumi.getChecksum().getValue());
2015-06-15 17:47:35 -07:00
}
// Alternative way to open and read Zip files:
2015-12-15 11:47:04 -08:00
try(ZipFile zf = new ZipFile("test.zip")) {
Enumeration e = zf.entries();
while(e.hasMoreElements()) {
ZipEntry ze2 = (ZipEntry)e.nextElement();
System.out.println("File: " + ze2);
// ... and extract the data as before
}
2015-06-15 17:47:35 -07:00
}
}
2015-09-07 11:44:36 -06:00
}
/* Output: (Execute to see) */