Java Reference
In-Depth Information
A ZipEntry object represents an entry in an archive file in a ZIP file format. If you have archived 10 files in a file
called test.zip , each file in the archive is represented by a ZipEntry object in your program. A zip entry may be
compressed or uncompressed. When you read all files from a ZIP file, you read each of them as a ZipEntry object.
When you want to add a file to a ZIP file, you add a ZipEntry object to the ZIP file. The ZipEntry class has methods to
set and get information about an entry in a ZIP file.
ZipInputStream is a concrete decorator class in the InputStream class family; you use it to read data from a ZIP
file for each entry. ZipOutputStream is a concrete decorator class in the OutputStream class family; you use this class
to write data to a ZIP file for each entry. ZipFile is a utility class to read the entries from a ZIP file. You have the option
to use either the ZipInputStream class or the ZipFile class when you want to read entries from a ZIP file.
Here are the steps to create a ZIP file.
1.
Create a ZipOutputStream object.
2.
Create a ZipEntry object to represent an entry in the ZIP file.
3.
Add the ZipEntry to the ZipOutputStream .
4.
Write the contents of the entry to the ZipOutputStream .
5.
Close the ZipEntry .
6.
Repeat the previous four steps for each zip entry you want to add to the archive.
7. Close the ZipOutputStream .
You can create an object of ZipOutputStream using the name of the ZIP file. You need to create a
FileOutputStream object and wrap it inside a ZipOutputStream object as follows:
// Create a zip output stream
ZipOutputStream zos = new ZipOutputStream(
new FileOutputStream("ziptest.zip"));
You may use any other output stream concrete decorator to wrap your FileOutputStream object. For example,
you may want to use BufferedOutputStream for a better speed as follows:
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(
new FileOutputStream("ziptest.zip")));
Optionally, you can set the compression level for the ZIP file entries. By default, the compression level is set to
DEFAULT_COMPRESSION . For example, the following statement sets the compression level to BEST_COMPRESSION :
// Set the compression level for zip entries
zos.setLevel(Deflater.BEST_COMPRESSION);
You create a ZipEntry object using the file path for each entry and add the entry to the ZipOutputStream object
using its putNextEntry() method, like so:
ZipEntry ze = new ZipEntry("test1.txt")
zos.putNextEntry(ze);
Optionally, you can set the storage method for the zip entry to indicate if the zip entry is stored compressed or
uncompressed. By default, a zip entry is stored in a compressed form.
 
Search WWH ::




Custom Search