读取zip存档中的文本文件

我有zip存档,其中包含一堆纯文本文件。 我想解析每个文本文件数据。 这是我到目前为止所写的内容:

try { final ZipFile zipFile = new ZipFile(chooser.getSelectedFile()); final Enumeration 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 。 首先获取一个InputStream ,其中包含此zip文件条目的数据:

 InputStream input = zipFile.getInputStream(entry); 

然后将它包装在InputStreamReader (从二进制到文本解码)和BufferedReader (一次读取一行)中:

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

然后正常读取它的行。 像往常一样包装try/finally块中的所有适当位,以关闭所有资源。