Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read files in a .zip file in Java?

Tags:

java

zip

extract

I would like to parse a .zip file. The .zip file contains one folder. The folder in turn contains several files. I would like to read all files without writing the .zip file to disk. I have the following code:

        zipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();

        while(entries.hasMoreElements()){
            ZipEntry entry = entries.nextElement();
            InputStream stream = zipFile.getInputStream(entry);
            InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
            Scanner inputStream = new Scanner(reader);
            inputStream.nextLine();

            while (inputStream.hasNext()) {
                String data = inputStream.nextLine(); // Gets a whole line
                String[] line = data.split(SEPARATOR); // Splits the line up into a string array
            }

            inputStream.close();
            stream.close();
        }
        zipFile.close();

The problem is that this only works when the files are directly in the .zip file. How can I adapt my code so that it also works when the files are inside a folder in the .zip file?

like image 304
machinery Avatar asked Oct 27 '25 17:10

machinery


1 Answers

You could put the code that reads content inside an if

ZipEntry entry = entries.nextElement();
if (!entry.isDirectory()) {
    InputStream stream = zipFile.getInputStream(entry);
...
    stream.close();
}
like image 122
radoh Avatar answered Oct 30 '25 07:10

radoh