# 9-I/O
[原文鏈接](http://code.google.com/p/guava-libraries/wiki/IOExplained)?[譯文鏈接](http://ifeve.com/google-guava-io)?**譯者:**沈義揚
## 字節流和字符流
Guava使用術語”流” 來表示可關閉的,并且在底層資源中有位置狀態的I/O數據流。術語”字節流”指的是InputStream或OutputStream,”字符流”指的是Reader 或Writer(雖然他們的接口Readable 和Appendable被更多地用于方法參數)。相應的工具方法分別在[`ByteStreams`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/io/ByteStreams.html) 和[`CharStreams`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/io/CharStreams.html)中。
大多數Guava流工具一次處理一個完整的流,并且/或者為了效率自己處理緩沖。還要注意到,接受流為參數的Guava方法不會關閉這個流:關閉流的職責通常屬于打開流的代碼塊。
其中的一些工具方法列舉如下:
| **ByteStreams** | **CharStreams** |
|:--- |:--- |
| [`byte[] toByteArray(InputStream)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/io/ByteStreams.html#toByteArray%28java.io.InputStream%29) | [`String toString(Readable)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/io/CharStreams.html#toString%28java.lang.Readable%29) |
| N/A | [`List<String> readLines(Readable)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/CharStreams.html#readLines%28java.lang.Readable%29) |
| [`long copy(InputStream, OutputStream)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/io/ByteStreams.html#copy%28java.io.InputStream, java.io.OutputStream%29) | [`long copy(Readable, Appendable)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/io/CharStreams.html#copy%28java.lang.Readable, java.lang.Appendable%29) |
| [`void readFully(InputStream, byte[])`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/io/ByteStreams.html#readFully%28java.io.InputStream, byte[]%29) | N/A |
| [`void skipFully(InputStream, long)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteStreams.html#skipFully%28java.io.InputStream, long%29) | [`void skipFully(Reader, long)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/CharStreams.html#skipFully%28java.io.Reader, long%29) |
| [`OutputStream nullOutputStream()`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteStreams.html#nullOutputStream%28%29) | [`Writer nullWriter()`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/CharStreams.html#nullWriter%28%29) |
**關于InputSupplier 和OutputSupplier要注意:**
在ByteStreams、CharStreams以及com.google.common.io包中的一些其他類中,某些方法仍然在使用InputSupplier和OutputSupplier接口。這兩個借口和相關的方法是不推薦使用的:它們已經被下面描述的source和sink類型取代了,并且最終會被移除。
## 源與匯
通常我們都會創建I/O工具方法,這樣可以避免在做基礎運算時總是直接和流打交道。例如,Guava有Files.toByteArray(File) 和Files.write(File, byte[])。然而,流工具方法的創建經常最終導致散落各處的相似方法,每個方法讀取不同類型的源
或寫入不同類型的匯[sink]。例如,Guava中的Resources.toByteArray(URL)和Files.toByteArray(File)做了同樣的事情,只不過數據源一個是URL,一個是文件。
為了解決這個問題,Guava有一系列關于源與匯的抽象。源或匯指某個你知道如何從中打開流的資源,比如File或URL。源是可讀的,匯是可寫的。此外,源與匯按照字節和字符劃分類型。
| **字節** | **字符** |
|:--- |:--- |
| **讀** | [`ByteSource`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/io/ByteSource.html) | [`CharSource`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/io/CharSource.html) |
| **寫** | [`ByteSink`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/io/ByteSink.html) | [`CharSink`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/io/CharSink.html) |
源與匯API的好處是它們提供了通用的一組操作。比如,一旦你把數據源包裝成了ByteSource,無論它原先的類型是什么,你都得到了一組按字節操作的方法。
### 創建源與匯
Guava提供了若干源與匯的實現:
| **字節** | **字符** |
|:--- |:--- |
| [`Files.asByteSource(File)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html#asByteSource%28java.io.File%29) | [`Files.asCharSource(File, Charset)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html#asCharSource%28java.io.File, java.nio.charset.Charset%29) |
| [`Files.asByteSink(File, FileWriteMode...)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html#asByteSink%28java.io.File, com.google.common.io.FileWriteMode...%29) | [`Files.asCharSink(File, Charset, FileWriteMode...)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html#asCharSink%28java.io.File, java.nio.charset.Charset, com.google.common.io.FileWriteMode...%29) |
| [`Resources.asByteSource(URL)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Resources.html#asByteSource%28java.net.URL%29) | [`Resources.asCharSource(URL, Charset)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Resources.html#asCharSource%28java.net.URL, java.nio.charset.Charset%29) |
| [`ByteSource.wrap(byte[])`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSource.html#wrap%28byte[]%29) | [`CharSource.wrap(CharSequence)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/CharSource.html#wrap%28java.lang.CharSequence%29) |
| [`ByteSource.concat(ByteSource...)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSource.html#concat%28com.google.common.io.ByteSource...%29) | [`CharSource.concat(CharSource...)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/CharSource.html#concat%28com.google.common.io.CharSource...%29) |
| [`ByteSource.slice(long, long)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSource.html#slice%28long, long%29) | N/A |
| N/A | [`ByteSource.asCharSource(Charset)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSource.html#asCharSource%28java.nio.charset.Charset%29) |
| N/A | [`ByteSink.asCharSink(Charset)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSink.html#asCharSink%28java.nio.charset.Charset%29) |
此外,你也可以繼承這些類,以創建新的實現。
注:把已經打開的流(比如InputStream)包裝為源或匯聽起來是很有誘惑力的,但是應該避免這樣做。源與匯的實現應該在每次openStream()方法被調用時都創建一個新的流。始終創建新的流可以讓源或匯管理流的整個生命周期,并且讓多次調用openStream()返回的流都是可用的。此外,如果你在創建源或匯之前創建了流,你不得不在異常的時候自己保證關閉流,這壓根就違背了發揮源與匯API優點的初衷。
### 使用源與匯
一旦有了源與匯的實例,就可以進行若干讀寫操作。
**通用操作**
所有源與匯都有一些方法用于打開新的流用于讀或寫。默認情況下,其他源與匯操作都是先用這些方法打開流,然后做一些讀或寫,最后保證流被正確地關閉了。這些方法列舉如下:
* openStream():根據源與匯的類型,返回InputStream、OutputStream、Reader或者Writer。
* openBufferedStream():根據源與匯的類型,返回InputStream、OutputStream、BufferedReader或者BufferedWriter。返回的流保證在必要情況下做了緩沖。例如,從字節數組讀數據的源就沒有必要再在內存中作緩沖,這就是為什么該方法針對字節源不返回BufferedInputStream。字符源屬于例外情況,它一定返回BufferedReader,因為BufferedReader中才有readLine()方法。
**源操作**
| **字節源** | **字符源** |
|:--- |:--- |
| [`byte[] ? read()`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSource.html#read%28%29) | [`String ? read()`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/CharSource.html#read%28%29) |
| N/A | [`ImmutableList<String> ? readLines()`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/CharSource.html#readLines%28%29) |
| N/A | [`String ? readFirstLine()`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/CharSource.html#readFirstLine%28%29) |
| [`long ? copyTo(ByteSink)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSource.html#copyTo%28com.google.common.io.ByteSink%29) | [`long ? copyTo(CharSink)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/CharSource.html#copyTo%28com.google.common.io.CharSink%29) |
| [`long ? copyTo(OutputStream)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSource.html#copyTo%28java.io.OutputStream%29) | [`long ? copyTo(Appendable)` ?](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/CharSource.html#copyTo%28java.lang.Appendable%29) |
| [`long ? size()`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSource.html#size%28%29) (in bytes) | N/A |
| [`boolean ? isEmpty()`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSource.html#isEmpty%28%29) | [`boolean ? isEmpty()`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/CharSource.html#isEmpty%28%29) |
| [`boolean ? contentEquals(ByteSource)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSource.html#contentEquals%28com.google.common.io.ByteSource%29) | N/A |
| [`HashCode ? hash(HashFunction)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSource.html#hash%28com.google.common.hash.HashFunction%29) | N/A |
匯操作
| **字節匯** | **字符匯** |
|:--- |:--- |
| [`void write(byte[])`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSink.html#write%28byte[]%29) | [`void write(CharSequence)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/CharSink.html#write%28java.lang.CharSequence%29) |
| [`long writeFrom(InputStream)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSink.html#writeFrom%28java.io.InputStream%29) | [`long writeFrom(Readable)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/CharSink.html#writeFrom%28java.lang.Readable%29) |
| N/A | [`void writeLines(Iterable<? extends CharSequence>)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/CharSink.html#writeLines%28java.lang.Iterable%29) |
| N/A | [`void writeLines(Iterable<? extends CharSequence>, String)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/CharSink.html#writeLines%28java.lang.Iterable, java.lang.String%29) |
### 范例
```
//Read the lines of a UTF-8 text file
ImmutableList<String> lines = Files.asCharSource(file, Charsets.UTF_8).readLines();
//Count distinct word occurrences in a file
Multiset<String> wordOccurrences = HashMultiset.create(
Splitter.on(CharMatcher.WHITESPACE)
.trimResults()
.omitEmptyStrings()
.split(Files.asCharSource(file, Charsets.UTF_8).read()));
//SHA-1 a file
HashCode hash = Files.asByteSource(file).hash(Hashing.sha1());
//Copy the data from a URL to a file
Resources.asByteSource(url).copyTo(Files.asByteSink(file));
```
## 文件操作
除了創建文件源和文件的方法,Files類還包含了若干你可能感興趣的便利方法。
| [`createParentDirs(File)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/io/Files.html#createParentDirs%28java.io.File%29) | 必要時為文件創建父目錄 |
|:--- |:--- |
| [`getFileExtension(String)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/io/Files.html#getFileExtension%28java.lang.String%29) | 返回給定路徑所表示文件的擴展名 |
| [`getNameWithoutExtension(String)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html#getNameWithoutExtension%28java.lang.String%29) | 返回去除了擴展名的文件名 |
| [`simplifyPath(String)`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/io/Files.html#simplifyPath%28java.lang.String%29) | 規范文件路徑,并不總是與文件系統一致,請仔細測試 |
| [`fileTreeTraverser()`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html#fileTreeTraverser%28%29) | 返回TreeTraverser用于遍歷文件樹 |
- Google Guava官方教程(中文版)
- 1-基本工具
- 1.1-使用和避免null
- 1.2-前置條件
- 1.3-常見Object方法
- 1.4-排序: Guava強大的”流暢風格比較器”
- 1.5-Throwables:簡化異常和錯誤的傳播與檢查
- 2-集合
- 2.1-不可變集合
- 2.2-新集合類型
- 2.3-強大的集合工具類:java.util.Collections中未包含的集合工具
- 2.4-集合擴展工具類
- 3-緩存
- 4-函數式編程
- 5-并發
- 5.1-google Guava包的ListenableFuture解析
- 5.2-Google-Guava Concurrent包里的Service框架淺析
- 6-字符串處理:分割,連接,填充
- 7-原生類型
- 9-I/O
- 10-散列
- 11-事件總線
- 12-數學運算
- 13-反射