Java Reference
In-Depth Information
// To store the zip entry in a compressed form
ze.setMethod(ZipEntry.DEFLATED);
// To store the zip entry in an uncompressed form
ze.setMethod(ZipEntry.STORED);
Write the content of the entry you have added in the previous step to the ZipOutputStream object. Since a
ZipEntry object represents a file, you will need to read the file by creating a FileInputStream object.
// Create an input stream to read data for the entry file
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("test1.txt"));
byte[] buffer = new byte[1024];
int count = -1;
// Write the data for the entry
while((count = bis.read(buffer)) != -1) {
zos.write(buffer, 0, count);
}
bis.close();
Now, close the entry using the closeEntry() method of the ZipOutputStream .
// Close the zip entry
zos.closeEntry();
Repeat the previous steps for each entry that you want to add to the zip file.
Finally, you need to close the ZipOutputStream .
// Close the zip entry
zos.close()
Listing 9-3 demonstrates how to create a ZIP file. It adds two files called test1.txt and notes\test2.txt to the
testzip.zip file. The program expects these files in the current working directory. If the files do not exist, the program
prints an error message with the path of the expected files. When the program finishes successfully, a testzip.zip file
is created in the current directory that you can open using a ZIP file utility such as WinZip on Windows. The program
prints the path of the newly created ZIP file. You may get a different output when you run the program.
Listing 9-3. Creating a ZIP File
// ZipUtility.java
package com.jdojo.archives;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.BufferedOutputStream;
 
Search WWH ::




Custom Search