如何在 Java 中读取 .zip 文件中的文件?

2024-01-02

我想解析 .zip 文件。 .zip 文件包含一个文件夹。该文件夹又包含多个文件。我想读取所有文件而不将 .zip 文件写入磁盘。我有以下代码:

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

问题是,这仅当文件直接位于 .zip 文件中时才有效。如何调整我的代码,使其在文件位于 .zip 文件的文件夹内时也能正常工作?


您可以将读取内容的代码放在if

ZipEntry entry = entries.nextElement();
if (!entry.isDirectory()) {
    InputStream stream = zipFile.getInputStream(entry);
...
    stream.close();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Java 中读取 .zip 文件中的文件? 的相关文章

随机推荐