[英]Google guava: Using `ByteSource` and `ByteSink` after deprecation of `InputSupplier` and `OutputSupplier` utilities
[英]how to use the InputSupplier or OutputSupplier api of Guava?
我是guava库的新手,我对InputSupplier和OutputSupplier很困惑。 根据javadoc,它们分别只是InputStream和OutputStream的工厂。 但是,我没有看到这两个接口有什么用处,有没有人能告诉我为什么我应该使用这两个API除了更高的抽象?
这两个接口的主要好处是它们允许库代码控制实际输入/输出对象的整个生命周期。 Guava的实用程序永远不会关闭您直接传入的InputStream
或OutputStream
,因为这可能不是您想要发生的。 即使他们这样做了,你仍然需要try
/ finally
处理创建对象的错误。 供应商是一种懒惰的回调,它允许一次性创建,使用和关闭实际对象,而不必进行大量丑陋的try
/ finally
和错误处理。
例如,只需查看将一个文件复制到另一个文件所需的代码(使用Guava实用程序将实际复制和流关闭代码最小化):
File in = ...
File out = ...
FileInputStream inStream = new FileInputStream(in);
boolean threw = true;
try {
/*
* Note how two try/finally blocks are needed here, in case creating
* outStream fails.
*/
FileOutputStream outStream = new FileOutputStream(out);
try {
ByteStreams.copy(inStream, outStream);
threw = false;
} finally {
Closeables.close(outStream, threw);
}
} finally {
Closeables.close(inStream, threw);
}
如果您使用供应商,请查看代码:
File in = ...
File out = ...
ByteStreams.copy(Files.newInputStreamSupplier(in),
Files.newOutputStreamSupplier(out));
使用Guava的InputSupplier / OutputSupplier,您不必自己处理实例化FileInputStreams / FileOutputStreams时抛出的各种IOExceptions。 当Guava调用InputSupplier.getInput()/ OutputSupplier.getOutput()工厂方法时,它会自动为您处理这些异常。
通过在这些工厂接口中封装输入/输出结构,您可以推迟实例化,从而推迟处理它们可能抛出的IOException / FileNotFoundException。 事实上,你推迟了它,它是为你处理它的番石榴。
然后你可以更换
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
doSomething(inputStream);
同
InputSupplier<FileInputStream> inputStreamSupplier = Files.newInputStreamSupplier(file);
doSomething(inputStreamSupplier);
编辑:另请参阅ColinD的答案,了解Guava如何在控制整个生命周期(即使用InputSupplier / OutputSupplier获取它们时)为您关闭这些输入/输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.