Java 读取 zip 存档中的文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4473256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading text files in a zip archive
提问by Amir Afghani
I have zip archive that contains a bunch of plain text files in it. I want to parse each text files data. Here's what I've written so far:
我有 zip 存档,其中包含一堆纯文本文件。我想解析每个文本文件数据。这是我到目前为止所写的内容:
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? I'm lost at the point where I have the ZipInputStream.
我需要一个 RandomAccessFile 来做到这一点吗?我在拥有 ZipInputStream 的地方迷路了。
采纳答案by Jon Skeet
No, you don't need a RandomAccessFile
. First get an InputStream
with the data for this zip file entry:
不,您不需要RandomAccessFile
. 首先获取InputStream
此 zip 文件条目的数据:
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
像往常一样将所有适当的位包裹在块中,以关闭所有资源。