简体   繁体   English

读取zip存档中的文本文件

[英]Reading text files in a zip archive

I have zip archive that contains a bunch of plain text files in it. 我有zip存档,其中包含一堆纯文本文件。 I want to parse each text files data. 我想解析每个文本文件数据。 Here's what I've written so far: 这是我到目前为止所写的内容:

try {
    final ZipFile zipFile = new ZipFile(chooser.getSelectedFile());
    final Enumeration<? extends ZipEntry> entries = zipFile.entries();
    ZipInputStream zipInput = null;

    while (entries.hasMoreElements()) {
        final ZipEntry zipEntry = entries.nextElement();
        if (!zipEntry.isDirectory()) {
            final String fileName = zipEntry.getName();
            if (fileName.endsWith(".txt")) {
                zipInput = new ZipInputStream(new FileInputStream(fileName));
                final RandomAccessFile rf = new RandomAccessFile(fileName, "r");
                String line;
                while((line = rf.readLine()) != null) {
                    System.out.println(line);
                }
                rf.close();
                zipInput.closeEntry();
            }
        }
    }
    zipFile.close();
}
catch (final IOException ioe) {
    System.err.println("Unhandled exception:");
    ioe.printStackTrace();
    return;
}

Do I need a RandomAccessFile to do this? 我需要一个RandomAccessFile吗? I'm lost at the point where I have the ZipInputStream. 我失去了我拥有ZipInputStream的地步。

No, you don't need a RandomAccessFile . 不,您不需要RandomAccessFile First get an InputStream with the data for this zip file entry: 首先获取一个包含此zip文件条目数据的InputStream

InputStream input = zipFile.getInputStream(entry);

Then wrap it in an InputStreamReader (to decode from binary to text) and a BufferedReader (to read a line at a time): 然后将它包装在InputStreamReader (从二进制到文本解码)和BufferedReader (一次读取一行)中:

BufferedReader br = new BufferedReader(new InputStreamReader(input, "UTF-8"));

Then read lines from it as normal. 然后正常读取它的线条。 Wrap all the appropriate bits in try/finally blocks as usual, too, to close all resources. 像往常一样在try/finally块中包装所有适当的位,以关闭所有资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM