|
ZipTest.java
Zip files with a ZipOutputStream.
For each file:
- create a ZipEntry
- put the entry in the output stream
- copy the file to the output stream
- close the entry
ZipOutputStream
|
+ ZipOutputStream(OutputStream)
+ putNextEntry(ZipEntry)
+ write(int)
+ closeEntry()
+ close()
|
Unzip files with a ZipFile.
For each ZipEntry:
- get an input stream for the entry
- open an output stream for the file
- copy the file to the output stream
- close the streams
ZipFile
|
+ ZipFile(File)
+ ZipFile(String)
+ entries() : Enumeration
+ getInputStream(ZipEntry) : InputStream
+ close()
|
|
void zipFiles(File[] files, File zipFile) throws IOException {
ZipOutputStream zip = new ZipOutputStream(
new BufferedOutputStream(
new FileOutputStream(zipFile)));
for (int i = 0; i < files.length; i++) {
InputStream in = new BufferedInputStream(
new FileInputStream(files[i]));
ZipEntry entry = new ZipEntry(files[i].getName());
zip.putNextEntry(entry);
int b;
while ((b = in.read()) != -1) {
zip.write(b);
}
zip.closeEntry();
in.close();
}
zip.close();
}
void unzipFiles(File file) throws IOException {
ZipFile zipFile = new ZipFile(file);
Enumeration entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
InputStream in = new BufferedInputStream(
zipFile.getInputStream(entry));
OutputStream out = new BufferedOutputStream(
new FileOutputStream(entry.getName()));
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
in.close();
out.close();
}
}
|
|