[英]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.