我有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;
}
Run Code Online (Sandbox Code Playgroud)
我需要一个RandomAccessFile吗?我失去了我拥有ZipInputStream的地步.
Jon*_*eet 40
不,你不需要RandomAccessFile.首先获取InputStream此zip文件条目的数据:
InputStream input = zipFile.getInputStream(entry);
Run Code Online (Sandbox Code Playgroud)
然后将其包装成InputStreamReader(从二进制到文本解码)和a BufferedReader(一次读取一行):
BufferedReader br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
Run Code Online (Sandbox Code Playgroud)
然后正常读取它的线条.try/finally像往常一样将所有适当的位包装在块中,以关闭所有资源.
| 归档时间: |
|
| 查看次数: |
26599 次 |
| 最近记录: |