[英]Reading text files in a zip archive
我有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;
}
我需要一個RandomAccessFile嗎? 我失去了我擁有ZipInputStream的地步。
不,您不需要RandomAccessFile
。 首先獲取一個包含此zip文件條目數據的InputStream
:
InputStream input = zipFile.getInputStream(entry);
然后將它包裝在InputStreamReader
(從二進制到文本解碼)和BufferedReader
(一次讀取一行)中:
BufferedReader br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
然后正常讀取它的線條。 像往常一樣在try/finally
塊中包裝所有適當的位,以關閉所有資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.