Java I/O 系統以四大抽象類為核心:
所有具體實現類(如 FileInputStream、FileReader)均繼承自這四大基類。
InputStream 抽象了「讀取資料」的方式OutputStream 抽象了「寫出資料」的方式-1 代表 EOF(串流結尾)int read() // 讀取單一位元組,填入 int 低 8 位,結尾回傳 -1
int read(byte[] buf) // 讀取最多 buf.length 位元組填入陣列
int read(byte[] buf, int off, int len) // 從 off 開始讀取 len 位元組
void write(int b) // 寫出 int 低 8 位
void write(byte[] buf) // 寫出整個陣列
void write(byte[] buf, int off, int len) // 從 off 寫出 len 位元組
File file = new File("D:\\demo.txt"); // 內容:「你好hello」
try (InputStream in = new FileInputStream(file)) {
int b;
while ((b = in.read()) != -1) {
System.out.print(Integer.toHexString(b & 0xff) + " ");
}
// 輸出:c4 e3 ba c3 68 65 6c 6c 6f
}
try (InputStream in = new FileInputStream(file)) {
byte[] buf = new byte[1024];
in.read(buf);
System.out.println(new String(buf, "GBK")); // 輸出:你好hello
}
關鍵點:中文在 GBK 編碼下佔 2 位元組,英文佔 1 位元組;位元組流不處理編碼轉換,需自行指定 charset 解碼為字串。
Reader/Writer 內部自動處理字元編碼轉換。常用橋接類:
InputStreamReader:位元組流 → 字元流(可指定 charset)OutputStreamWriter:字元流 → 位元組流配合緩衝流(BufferedReader/Writer)可大幅提升效能。
new String(bytes) 會用平台預設編碼(中文 Windows 為 GBK),跨平台必須顯式指定 new String(bytes, StandardCharsets.UTF_8)。