Java Reference
In-Depth Information
// Create a ZipFile object using the ZIP file name
ZipFile zf = new ZipFile("ziptest.zip");
// Get the enumeration for all zip entries and loop through them
Enumeration<? extends ZipEntry> e = zf.entries();
ZipEntry entry = null;
while (e.hasMoreElements()) {
entry = e.nextElement();
// Get the input stream for the current zip entry
InputStream is = zf.getInputStream(entry);
/* Read data for the entry using the is object */
// Print the name of the entry
System.out.println(entry.getName());
}
Java 8 added a new stream() method to the ZipFile class that returns a Stream of ZipEntry objects. I will cover
the Stream class in Chapter 13. Let's rewrite the above code using the Stream class and a lambda expression. The
revised code uses the latest addition to the Java languages: the Stream class and the lambda expression.
import java.io.IOException;
import java.io.InputStream;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
...
// Create a ZipFile object using the ZIP file name
ZipFile zf = new ZipFile("ziptest.zip");
// Get the Stream of all zip entries and apply some actions on each of them
Stream<? extends ZipEntry> entryStream = zf.stream();
entryStream.forEach(entry -> {
try {
// Get the input stream for the current zip entry
InputStream is = zf.getInputStream(entry);
/* Read data for the entry using the is object */
}
catch(IOException e) {
e.printStackTrace();
}
// Print the name of the entry
System.out.println(entry.getName());
});
Search WWH ::




Custom Search