读取zip存档中的文本文件 [英] Reading text files in a zip archive
问题描述
我的zip存档包含一堆纯文本文件。我想解析每个文本文件数据。这是我到目前为止写的:
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:
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;
}
我是否需要RandomAccessFile来执行此操作?我失去了我拥有ZipInputStream的地步。
Do I need a RandomAccessFile to do this? I'm lost at the point where I have the ZipInputStream.
推荐答案
不,您不需要 RandomAccessFile
。首先使用此zip文件条目的数据获取 InputStream
:
No, you don't need a RandomAccessFile
. First get an InputStream
with the data for this zip file entry:
InputStream input = zipFile.getInputStream(entry);
然后将其包装在 InputStreamReader
中(至从二进制解码到文本)和 BufferedReader
(一次读一行):
Then wrap it in an InputStreamReader
(to decode from binary to text) and a BufferedReader
(to read a line at a time):
BufferedReader br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
然后正常读取它的行。像往常一样包裹 try / finally
块中的所有相应位,以关闭所有资源。
Then read lines from it as normal. Wrap all the appropriate bits in try/finally
blocks as usual, too, to close all resources.
这篇关于读取zip存档中的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!