OnJava8-Examples/compression/ZipCompress.java

84 lines
2.5 KiB
Java
Raw Normal View History

2015-11-03 12:00:44 -08:00
// compression/ZipCompress.java
2016-12-30 17:23:13 -08:00
// (c)2017 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.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-06-15 17:47:35 -07:00
// Uses Zip compression to compress any
2016-01-25 18:05:55 -08:00
// number of files given on the command line
2016-07-28 13:42:03 -06:00
// {java ZipCompress ZipCompress.java}
2016-07-20 06:32:39 -06:00
// {ValidateByHand}
2015-06-15 17:47:35 -07:00
import java.util.zip.*;
import java.io.*;
import java.util.*;
public class ZipCompress {
2017-01-22 16:48:11 -08:00
public static void main(String[] args) {
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);
try(
InputStream in = new BufferedInputStream(
new FileInputStream(arg))
) {
2015-06-15 17:47:35 -07:00
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());
2017-01-22 16:48:11 -08:00
} catch(IOException e) {
throw new RuntimeException(e);
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");
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());
2017-01-22 16:48:11 -08:00
} catch(IOException e) {
throw new RuntimeException(e);
2015-06-15 17:47:35 -07:00
}
// Alternative way to open and read Zip files:
try(
ZipFile zf = new ZipFile("test.zip")
) {
2015-12-15 11:47:04 -08:00
Enumeration e = zf.entries();
while(e.hasMoreElements()) {
ZipEntry ze2 = (ZipEntry)e.nextElement();
System.out.println("File: " + ze2);
// ... and extract the data as before
}
2017-01-22 16:48:11 -08:00
} catch(IOException e) {
throw new RuntimeException(e);
2015-06-15 17:47:35 -07:00
}
}
2015-09-07 11:44:36 -06:00
}