Java 的 IO 分成兩大類。輸入流全部直接或間接繼承自 InputStream,是資料的來源,透過 read() 讀取位元組;輸出流繼承自 OutputStream,是資料的去向,透過 write() 寫入位元組。多數輸入輸出流成對出現:有 XXXInputStream 就有 XXXOutputStream。SequenceInputStream 與 StringBufferInputStream 是少數例外。此外,read、write、close 都可能拋出 IOException。
前者以 byte 陣列作為資料源,read 時從陣列取值;若建構時傳入 null,不會立刻出錯,但一呼叫 read 就會 NullPointerException。後者內部維護一個 byte 陣列用來累積寫入的資料,可在建構時指定初始大小,未指定則為 32 位元組;空間不足時會自動呼叫 ensureCapacity 擴容,所以不必擔心寫入過多而越界。
private static void testByteArrayInputOutStream {
byte[] bytes = "I am iSpring".getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int length = 0;
try {
while ((length = bais.read(buf)) > 0) {
baos.write(buf, 0, length);
}
System.out.println(baos.toString("UTF-8"));
bais.close();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
以檔案為資料源。若指定的 File 不存在、指向目錄而非檔案,或基於其他原因無法開啟,建構階段就會拋 FileNotFoundException。FileOutputStream 同理,無法建立或寫入時一樣在建構階段失敗。若輸出檔已存在,可傳入 boolean 的 append 參數決定要附加還是覆寫。
private static void testFileInputOutStream() {
try {
String inputFileName = "D:\\iWork\\file1.txt";
String outputFileName = "D:\\iWork\\file2.txt";
FileInputStream fis = new FileInputStream(inputFileName);
FileOutputStream fos = new FileOutputStream(outputFileName);
byte[] buf = new byte[1024];
int length = 0;
while ((length = fis.read(buf)) > 0) {
fos.write(buf, 0, length);
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
這對搭檔用於兩個線程之間的管道通訊:一個線程寫、一個線程讀。可用建構參數或 connect() 綁定,綁定後 read 會主動取走寫入的資料。read 是阻塞式的——若上游一直沒寫,它就一直卡住。單獨使用其中任何一個都會得到 IOException: Pipe Not Connected。
public class WriterThread extends Thread {
PipedOutputStream pos = null;
public WriterThread(PipedOutputStream pos) { this.pos = pos; }
@Override public void run() {
String message = "這條信息來自於 WriterThread。";
try {
System.out.println("WriterThread 發送信息");
this.pos.write(message.getBytes("UTF-8"));
this.pos.close();
} catch (IOException e) { e.printStackTrace(); }
}
}
public class ReaderThread extends Thread {
private PipedInputStream pis = null;
public ReaderThread(PipedInputStream pis) { this.pis = pis; }
@Override public void run() {
byte[] buf = new byte[1024 * 8];
try {
System.out.println("ReaderThread 阻塞式地等待接收數據……");
int length = pis.read(buf);
System.out.println(new String(buf, 0, length, "UTF-8"));
pis.close();
} catch (IOException e) { e.printStackTrace(); }
}
}
// 測試
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
pos.connect(pis);
new ReaderThread(pis).start();
new WriterThread(pos).start();
即使先啟動 ReaderThread,它也會乖乖阻塞等待。要注意管道是單向且容量有限的,寫入端負責阻塞,設計時必須確保讀寫兩端都會被執行,否則容易死鎖。
ObjectOutputStream 提供 writeBoolean、writeInt、writeLong、writeFloat、writeDouble、writeChar、writeUTF 等一系列方法,可在建構時包一個底層串流,把基本型別與 String 直接寫入。writeObject 則把實作了 Serializable 的物件序列化後寫出。ObjectInputStream 有完全對應的 readXXX 系列。
public class Person implements Serializable {
private String name = "";
private int age = 0;
public Person(String name, int age) { this.name = name; this.age = age; }
public String getName() { return name; }
public int getAge() { return age; }
}
// 序列化
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
String description = "下面是人員數組";
Person[] persons = new Person[]{
new Person("iSpring", 26), new Person("Mr.Sun", 27), new Person("Miss.Zhou", 27)
};
oos.writeObject(description);
oos.writeInt(persons.length);
for (Person person : persons) oos.writeObject(person);
oos.close();
// 反序列化
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.println((String) ois.readObject());
int personCount = ois.readInt();
for (int i = 0; i < personCount; i++) {
Person person = (Person) ois.readObject();
System.out.println("姓名: " + person.getName() + ", 年齡: " + person.getAge());
}
Serializable 是標記介面,不需實作任何方法。最關鍵的一條規則:readXXX 的呼叫順序必須與 writeXXX 完全一致。若寫入時用 writeFloat(4 位元組)而讀取時用 readInt(也是 4 位元組),程式不會報錯,但你拿到的已經是錯的資料——這是最難查的一类 bug。另外別忘了 serialVersionUlD,欄位變動後沒有它會直接 InvalidClassException。
把兩個或多個 InputStream 在邏輯上串成一個:先讀 in1,讀完接著讀 in2。也因為如此,並不存在 SequenceOutputStream——把一個輸出流拆成多個是沒有意義的。
FileInputStream fis1 = new FileInputStream(inputFileName1); FileInputStream fis2 = new FileInputStream(inputFileName2); SequenceInputStream sis = new SequenceInputStream(fis1, fis2); FileOutputStream fos = new FileOutputStream(outputFileName); byte[] buf = new byte[1024]; int length = 0; while ((length = sis.read(buf)) > 0) fos.write(buf, 0, length); sis.close(); fos.close();
可傳入字串以位元組形式讀取,內部主要呼叫 String 的 charAt。它沒有對應的 StringBufferOutputStream,因為直接 new String(byte[]) 就够了,反過來做毫無意義。這個類本身有缺陷:它無法正確處理非 ASCII 字元,把 char 直接當 byte 用會讓中文變亂碼,因此已被標記為 Deprecated,官方建議改用 StringReader。
Filter 系列建構時接收一個串流並存在 in 欄位中,其每個方法都只是轉手呼叫 in 的對應方法,本身幾乎不做事。它的價值在於提供一個「可被 Decorator 鏈式包裝」的骨架:子類只需覆寫部分方法,就能在不改變介面的前提下加上新特性。
InputStream is = getInputStreamBySomeway(); BufferedInputStream bis = new BufferedInputStream(is); DataInputStream dis = new DataInputStream(bis); // 現在就能用 dis.readInt() 等,既有緩衝加速又有型別化讀取
輸出端同理:
OutputStream os = getOutputStreamBySomeway(); BufferedOutputStream bos = new BufferedOutputStream(os); DataOutputStream dos = new DataOutputStream(bos); // dos.writeInt(...) 兼得效率與便利
BufferedInputStream 內部有一個位元組緩衝區(預設 8192 位元組,可自訂)。read 時先從緩衝區取,取空了才真的去讀底層串流,而且一次讀一大塊填滿緩衝區,大幅降低實際 IO 次數。BufferedOutputStream 則把寫入先攢在緩衝區,填滿時才呼叫 flushBuffer 真正寫出並清空。
這裡有個實務上極重要的細節:BufferedOutputStream 的資料可能還躺在記憶體裡。因此 try-with-resources 或 finally 中關閉外層串流是必須的——close 會自動 flush;若只 flush 不 close,資料會寫出但底層資源未釋放。
FileInputStream fis = new FileInputStream(inputFileName); BufferedInputStream bis = new BufferedInputStream(fis, 1024 * 10); FileOutputStream fos = new FileOutputStream(outputFileName); BufferedOutputStream bos = new BufferedOutputStream(fos, 1024 * 10); byte[] buf = new byte[1024]; int length = 0; while ((length = bis.read(buf)) > 0) bos.write(buf, 0, length); bis.close(); bos.close();
把這些類放在一起看,Java IO 的設計就清楚了:最底層是節點流(File、ByteArray、Piped)負責真實的資料來源與去向;中間是裝飾流(Buffered、Data、Object、PrintStream)負責加特性。你要做的不是記住幾十個類,而是學會「按需堆疊」——先決定兩端節點,再依序套上需要的功能層,順序由內而外,關閉由外而內。