寫一支讀寫程式時用了 InputStream 的 reset(),結果直接失敗。翻 JDK 源碼才發現原因:BufferedInputStream 覆寫了父類 FilterInputStream 的 mark 與 reset,具備回退能力;而 FileInputStream 沒有覆寫 InputStream 的這兩個方法,因此根本不支援。
mark 的契約
JDK 對 mark(int readlimit) 的說明是:在輸入流中標記目前位置,後續呼叫 reset() 會把流重新定位到最後標記處,以便重讀相同位元組。readlimit 則是「在標記失效前允許讀取的最大位元組數」。
把它想成書籤:mark 之後,在讀出 readlimit 個位元組以內呼叫 reset(),都能回到書籤處重讀;一旦讀超過這個數量,書籤就失效,reset() 拿不回原本的資料。所以 mark(10) 表示只保證 10 個位元組內有效。
兩種實作對比
// FilterInputStream:只是轉呼叫,能力取決於底層
public synchronized void mark(int readlimit) { in.mark(readlimit); }
public synchronized void reset() throws IOException { in.reset(); }
public boolean markSupported() { return in.markSupported(); }
// BufferedInputStream:真正實作
public synchronized void mark(int readlimit) {
marklimit = readlimit;
markpos = pos;
}
public synchronized void reset() throws IOException {
getBufIfOpen();
if (markpos < 0) throw new IOException("Resetting to invalid mark");
pos = markpos;
}
public boolean markSupported() { return true; }
// InputStream:預設什麼都不做
public synchronized void mark(int readlimit) {}
public synchronized void reset() throws IOException {
throw new IOException("mark/reset not supported");
}
public boolean markSupported() { return false; }
可移植的寫法
import java.io.*;
public class TestInputStream {
public void read(InputStream in) throws IOException {
if (in == null) {
return;
}
in.mark(1);
in.read(); // 第一次讀取
in.reset(); // 回到標記處
in.read(); // 第二次讀取結果與第一次相同
}
public static void main(String[] args) throws IOException {
TestInputStream test = new TestInputStream();
String fileName = "F:/Google.txt";
InputStream in1 = new FileInputStream(new File(fileName));
if (!in1.markSupported()) {
in1 = new BufferedInputStream(in1); // 關鍵:自動包一層
}
test.read(in1);
byte[] buf = new byte[100];
while (in1.read(buf, 0, buf.length) != -1) {
System.out.println(buf);
}
System.out.println("Success!");
}
}
reset 的兩種情況
當 markSupported() 為 true:若建立流之後沒呼叫過 mark,或自最後一次 mark 後已讀取的位元組數超過 readlimit,reset() 可以拋出 IOException;否則必須讓 mark 之後讀過的資料重新提供給後續的 read()。
當 markSupported() 為 false:reset() 可能拋出 IOException;若不拋出,流會被設為某種固定狀態,具體行為由該類型的輸入流決定。InputStream 的 reset 除了拋例外不做任何事。
實務結論很明確:任何需要重讀的場合,先檢查 markSupported(),不支援就用 BufferedInputStream 包一層,並把 readlimit 設得比實際要回退的位元組數更大,這是最不容易出錯的做法。