Java IO 緩衝流本身不具備直接的 I/O 功能,它的作用是為現有的流「穿上一層外衣」,透過引入緩衝區機制,大幅提升讀寫效率。當應用程式頻繁對檔案或其他目標進行讀寫操作時,若每次都直接與底層系統交互,效能會顯著下降。緩衝流先將資料暫存於記憶體緩衝區,待累積一定量後再一次性寫入或讀取,從而減少系統呼叫次數,是 IO 操作中不可或缺的效能優化手段。
根據處理資料單位不同,緩衝流分為位元組緩衝流與字元緩衝流兩大類:
透過包裝 FileOutputStream,將資料先寫入緩衝區,再透過 flush() 強制刷新至檔案,關閉流時也會自動刷新一次。
public static void main(String[] args) {
try {
OutputStream out = new FileOutputStream("L:\\test.txt");
BufferedOutputStream buf = new BufferedOutputStream(out);
String data = "好好學習,天天向上";
buf.write(data.getBytes()); // 寫入緩衝區
buf.flush(); // 刷新緩衝區,實際寫入檔案
buf.close(); // 關閉緩衝流(會自動刷新)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
建立時會在內部創建緩衝陣列,讀取時從緩衝區獲取資料,減少磁碟 I/O 次數。
public static void main(String[] args) {
try {
InputStream in = new FileInputStream("L:\\test.txt");
BufferedInputStream buf = new BufferedInputStream(in);
byte[] bytes = new byte[1024];
int len = -1;
StringBuffer sb = new StringBuffer();
while ((len = buf.read(bytes)) != -1) {
sb.append(new String(bytes, 0, len));
}
System.out.println("內容為:" + sb);
buf.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
適用於文字檔案寫入,可指定緩衝區大小,預設值通常足夠使用。
public static void main(String[] args) {
try {
Writer w = new FileWriter("L:\\test.txt");
BufferedWriter buf = new BufferedWriter(w);
buf.write("只需功夫深鐵杵磨成針");
buf.flush();
buf.close();
w.close();
} catch (IOException e) {
e.printStackTrace();
}
}
支援 readLine() 逐行讀取,是處理文字檔案的首選工具。
public static void main(String[] args) {
try {
Reader r = new FileReader("L:\\test.txt");
BufferedReader buf = new BufferedReader(r);
char[] data = new char[512];
int len = -1;
StringBuilder sb = new StringBuilder();
while ((len = buf.read(data)) != -1) {
sb.append(new String(data, 0, len));
}
System.out.println("內容是: " + sb);
buf.close();
r.close();
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedReader/BufferedWriter)flush() 或 close() 確保資料落盤掌握緩衝流的正確使用,能讓 Java IO 操作事半功倍,是每位 Java 開發者的必修課。