我发现 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/