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

二次信任 提交于 2019-12-12 16:16:11

问题


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?


回答1:


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();
}


来源:https://stackoverflow.com/questions/35313884/how-to-read-files-in-a-zip-file-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!