java - Guava Resources.readLines() 用于 Zip/Gzip 文件

标签 java url guava readline

我发现 Resources.readLines() 和 Files.readLines() 对于简化我的代码很有帮助。
问题是我经常从 URL(HTTP 和 FTP)读取 gzip 压缩的 txt 文件或 zip 存档中的 txt 文件。
有没有办法使用 Guava 的方法来读取这些 URL?或者这只能通过 Java 的 GZIPInputStream/ZipInputStream 实现?

最佳答案

您可以创建自己的ByteSource:

对于 GZip:

public class GzippedByteSource extends ByteSource {
  private final ByteSource source;
  public GzippedByteSource(ByteSource gzippedSource) { source = gzippedSource; }
  @Override public InputStream openStream() throws IOException {
    return new GZIPInputStream(source.openStream());
  }
}

然后使用它:

Charset charset = ... ;
new GzippedByteSource(Resources.asByteSource(url)).toCharSource(charset).readLines();

这是 Zip 的实现。这假设您只阅读了一项。

public static class ZipEntryByteSource extends ByteSource {
  private final ByteSource source;
  private final String entryName;
  public ZipEntryByteSource(ByteSource zipSource, String entryName) {
    this.source = zipSource;
    this.entryName = entryName;
  }
  @Override public InputStream openStream() throws IOException {
    final ZipInputStream in = new ZipInputStream(source.openStream());
    while (true) {
      final ZipEntry entry = in.getNextEntry();
      if (entry == null) {
        in.close();
        throw new IOException("No entry named " + entry);
      } else if (entry.getName().equals(this.entryName)) {
        return new InputStream() {
          @Override
          public int read() throws IOException {
            return in.read();
          }

          @Override
          public void close() throws IOException {
            in.closeEntry();
            in.close();
          }
        };
      } else {
        in.closeEntry();
      }
    }
  }
}

你可以这样使用它:

Charset charset = ... ;
String entryName = ... ; // Name of the entry inside the zip file.
new ZipEntryByteSource(Resources.asByteSource(url), entryName).toCharSource(charset).readLines();

关于java - Guava Resources.readLines() 用于 Zip/Gzip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32011825/

相关文章:

python - Python 中的 Google App Engine 文件夹 url

java - 使用 Guava MapMaker/CacheBuilder 处理空值

concurrency - 如何使用 Guava ListenableFuture 和 Futures.chain() 方法

java - AppCompatActivity 和 ActionBarActivity

java - 表格的绝对位置用什么度量单位表示?我可以用厘米来表达这个位置吗?

java - 如何打印JTable中选定的行

java - 使用 Guava 检查泛型类

Java:int和double做1亿次简单计算耗时0毫秒

java - 服务器返回 HTTP 响应代码 : 400

javascript - 将文件转换为 url 中的可下载文件 - javascript