InputStream.read() // 回傳 int (0-255 或 -1)
OutputStream.write(int b) // 參數 int,僅取低 8 位
Reader.read() // 回傳 int (0-65535 或 -1)
Writer.write(int c) // 參數 int,僅取低 16 位
但批次讀寫卻用 byte[]/char[]。
byte、short、char 參與運算時會**自動提升為 int** 進行運算,結果再截斷回原類型。I/O 方法回傳/參數直接用 int,避免呼叫端額外轉型與提升開銷。byte/char 需額外指令擴展/截斷。-1 表示「流結束」(EOF),若回傳 byte(-128~127)或 char(無符號 0~65535)無法同時表示有效資料與 EOF,int 完美涵蓋 -1 與所有合法位元組/字元值。read(byte[]) 回傳實際讀取位元組數(int),write(byte[]) 無回傳值,語意清晰。int b = in.read();
if (b != -1) {
byte actualByte = (byte) b; // 安全轉型,因 b 在 0-255 範圍
out.write(actualByte); // 自動提升為 int 傳遞
}
單位元介面用 int:承載 EOF(-1) 與完整值域、符合 JVM 運算習慣、歷史效能考量。
批次介面用陣列:追求吞吐量、減少呼叫開銷。
此設計兼顧正確性、效能與跨平台一致性,是 Java I/O 經典 API 設計智慧的體現。