Hey guys in this post, we will discuss reading the contents of a zip file using ZipFile package in Java. ZipFile is a java.util.zip
, it provides some really useful methods and constructor for reading the zip file. let’s look at some of the important methods and constructor.
Table of Contents
Constructors
ZipFile(String filePath)
: This constructor takes the string as parameter. We will pass the zip file path.
Ex: ZipFile(“D:\\test.zip”)ZipFile(File file)
: This constructor takes the file object as parameter. We will pass the object of the file.
Ex: ZipFile(new File(“D:\\test.zip”))
Methods
getComment(): String
– returns the zip file comment, or null if none.getEntry(String name): ZipEntry
– returns the zip file entry for the specified name, or null if not found.getInputStream(ZipEntry entry)
: InputStream – Returns an input stream for reading the contents of the specified zip file entry.getName(): String
– returns the path name of the ZIP file.entries(): Enumeration<? extends ZipEntry>
– returns an enumeration of the ZIP file entries.
Let’s look at an example, i have a zip file it contains few files like, excel, pdf, image etc and i stored it in my D:// drive.
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ReadZipFile {
public static void main(String[] args) throws IOException {
ZipFile zip = null;
try {
zip = new ZipFile("D:\\test.zip");
for (Enumeration<?> e = zip.entries(); e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
if (!entry.isDirectory()) {
System.out.println(entry.getName());
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
zip.close();
}
}
}
Here, the important methods to keep in mind is that,
isDirectory()
This will return boolean telling that whether the zip file contains any folder or not. Here i am ignoring the directory.hasMoreElements()
This will return boolean letting us know whether the elements are present or not
This will produce the following output –
chage.png
16001
-----------------------------
fr_leading traling vth spec chars_CSV (1).csv
576
-----------------------------
Pro Angular 6, 3rd Edition.pdf
19403051
-----------------------------
That’s it for this post, i will see you in the next post.
Reference links: