Java Reference
In-Depth Information
while (bis.available() > 0) {
fileOutput.write(bis.read());
}
}
System.out.println("Written :"
+ entry.getName());
}
}
} catch (IOException e) {
e.printStackTrace();
}
How It Works
To work with the contents of a .
Zip
archive, create a
ZipFile
object. A
ZipFile
object can be instantiated, passing the name of a .
zip
archive to the constructor. After
creating the object, you gain access to the specified
.zip
file information. Each
ZipFile
object will contain a collection of entries that represent the directories and
files contained within the archive, and by iterating through the entries you can obtain
information on each of the compressed files. Each
ZipEntry
instance will have the
compressed and uncompressed size, the name, and the input stream of the uncom-
pressed bytes.
The uncompressed bytes can be read into a byte buffer by generating an
In-
putStream
, and later (in our case) written to a file. Using the
FileStream
, it is
possible to determine how many bytes can be read without blocking the process. Once
the determined number bytes has been read, then those bytes are written to the output
file. This process continues until the total number of bytes has been read.
Note
Reading the entire file into memory may not be a good idea if the file is ex-
tremely large. If you need to work with a large file, it's best to first write it in an uncom-
pressed format to disk (as in the example) and then open it and load it in chunks. If the
file that you are working on is not large (you can limit the size by checking the
getS-
ize()
method), you can probably load it in memory.