如何在Java中读取.zip文件中的文件? [英] How to read files in a .zip file in Java?

查看:1014
本文介绍了如何在Java中读取.zip文件中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析一个.zip文件. .zip文件包含一个文件夹.该文件夹依次包含几个文件.我想在不将.zip文件写入磁盘的情况下读取所有文件.我有以下代码:

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

问题在于,这仅在文件直接位于.zip文件中时有效.当文件位于.zip文件中的文件夹内时,如何修改代码,使其也起作用?

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?

推荐答案

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

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

这篇关于如何在Java中读取.zip文件中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆