【问题标题】:A reader for getting text lines from a zipped text file从压缩文本文件中获取文本行的阅读器
【发布时间】:2013-10-15 06:10:37
【问题描述】:

总结:拥有包含a.txt 的a.zip 的字节图像,我怎样才能获得一个干净且正确的阅读器,它返回文本文件的行?

我确实将 zip 文件的图像从 Web 服务下载到 byte[] content。我想写一个类似

的方法
private BufferedReader contentToBufferedReader(byte[] content)

这将返回一个可以像这样使用的阅读器

reader = contentToBufferedReader(content);
while ((line = reader.readLine()) != null) {
    processThe(line);
}
reader.close()

到目前为止,我已经(更新)

private BufferedReader contentToBufferedReader(byte[] content) {

    ByteArrayInputStream bais = new ByteArrayInputStream(content);
    ZipInputStream zipStream = new ZipInputStream(bais);
    BufferedReader reader = null;

    try {
        ZipEntry entry = zipStream.getNextEntry();

        // I need only the first (and the only) entry from the zip file.
        if (entry != null) {
            reader = new BufferedReader(new InputStreamReader(zipStream, "UTF-8"));
            System.out.println("contentToBufferedReader(): success");
        }
    }
    catch (IOException e) {
        System.out.println("contentToBufferedReader(): failed...");
        System.out.println(e.getMessage());
    }

    return reader;
}

我不确定当出现故障时如何关闭所有流对象。此外,如果reader 成功返回、使用和关闭,我不知道如何关闭它们。

【问题讨论】:

  • 感谢 Katja 提供有关如何装饰 zipStream 的提示。我已经修改了这个问题,因此它不应被视为与您提到的问题的重复。

标签: java android zip inputstream bufferedreader


【解决方案1】:

这将一次性取出所有字节(为方便起见,使用 guava ByteStreams)

ZipEntry entry = zipStream.getNextEntry();
while (entry != null) {
  if (!entry.isDirectory()) {
    String filename = entry.getName();//this includes the path!
    byte[] data = ByteStreams.toByteArray(zipStream);
    //do something with the bytes 
  }
  entry = zipIn.getNextEntry();
}

你可以得到这样的读者:

InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(data)));

当您调用 zipStream.getNextEntry() 时,zipStream 会前进。我还认为流不支持标记和重置 iirc,这意味着您只能读取一次(因此在将其传递给可能需要随机访问的其他处理之前立即将其全部取出)

【讨论】:

  • +1 感谢您教我entry.isDirectory()。否则,如果可以避免的话,我宁愿不将zipStream 的内容提取到byte[]。另外,我宁愿只在一个地方调用zipStream.getNextEntry()——在while 条件下。
  • 很高兴为您提供帮助。请注意,即使您不一次提取所有字节,也要确保只读取一次。我做了噩梦发现这一点。
【解决方案2】:

查看此主题,您可能需要先解压缩文件,然后才能阅读。

What is a good Java library to zip/unzip files?

【讨论】:

  • +1 链接。我发现zip4j 可以很好地替代 Android 标准 zip 支持。我得到的 zip 图像似乎使用 zip64,ZipInputStream 不支持。
猜你喜欢
  • 2012-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-12
  • 1970-01-01
  • 2015-11-11
相关资源
最近更新 更多