收納進此專輯:I/O流官方中文指南系列概述及索引
大部分內容來自 The Java? Tutorials 官方指南,其余來自別處如ifeve的譯文、imooc、書籍Android面試寶典等等。
作者: @youyuge
個人博客站點: https://youyuge.cn
一、字節(jié)流Byte Streams的定義
Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream
and OutputStream
.
There are many byte stream classes. To demonstrate how byte streams work, we'll focus on the file I/O byte streams, FileInputStream
and FileOutputStream
. Other kinds of byte streams are used in much the same way; they differ mainly in the way they are constructed.
- 我們的Java程序使用字節(jié)流來輸入輸出8比特(bit)的字節(jié)。所有的字節(jié)流的類都繼承自InputStream和OutputStream。
- 有很多字節(jié)流的類。為了說明字節(jié)流如何工作,我們將關注文件的I/O字節(jié)流FileInputStream 和 FileOutputStream。其他種類的字節(jié)流大部分使用上類似,只是在內部構造的方式上不同。
二、字節(jié)流的使用
我們使用如下類,在倆txt之間進行復制,一次復制一個字節(jié)byte。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
CopyBytes spends most of its time in a simple loop that reads the input stream and writes the output stream, one byte at a time, as shown in the following figure.
- 復制字節(jié)在讀取輸入流和寫輸出流上這個簡單的循環(huán)上花費了最多的時間,一次復制一個字節(jié)(可用別的方法一次多個)。如下圖所示:

三、請記得關閉流
Closing a stream when it's no longer needed is very important — so important that CopyBytes uses a finally block to guarantee that both streams will be closed even if an error occurs. This practice helps avoid serious resource leaks.
- 及時關閉不再需要的流非常重要,防止內存泄漏。用finally語句塊確保流一定會被關閉,哪怕中間出錯了。
四、什么時候不使用字節(jié)流
CopyBytes seems like a normal program, but it actually represents a kind of low-level I/O that you should avoid. Since xanadu.txt contains character data, the best approach is to use character streams, as discussed in the next section. There are also streams for more complicated data types. Byte streams should only be used for the most primitive I/O.
- 上面那種方式的復制字節(jié)是低級的I/O方式,我們應該避免使用。既然txt中包含的是字符數(shù)據(jù),最好的方法是使用字符流charater streams。字節(jié)流是最原始的I/O方式。
So why talk about byte streams? Because all other stream types are built on byte streams.
- 既然如此我們?yōu)楹我懻撟止?jié)流?因為別的形式的流類型是在字節(jié)流的基礎上構建的。