首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java I/O 流核心概念與實戰總結

     編輯:Java 綜合教學

四大抽象基類

Java I/O 系統以四大抽象類為核心:

  • InputStream / OutputStream:面向位元組的輸入/輸出流
  • Reader / Writer:面向字元的輸入/輸出流

所有具體實現類(如 FileInputStream、FileReader)均繼承自這四大基類。

位元組流詳解

核心契約

  • InputStream 抽象了「讀取資料」的方式
  • OutputStream 抽象了「寫出資料」的方式
  • 讀到 -1 代表 EOF(串流結尾)

InputStream 關鍵方法

int read()                    // 讀取單一位元組,填入 int 低 8 位,結尾回傳 -1
int read(byte[] buf)          // 讀取最多 buf.length 位元組填入陣列
int read(byte[] buf, int off, int len) // 從 off 開始讀取 len 位元組

OutputStream 關鍵方法

void write(int b)                 // 寫出 int 低 8 位
void write(byte[] buf)            // 寫出整個陣列
void write(byte[] buf, int off, int len) // 從 off 寫出 len 位元組

FileInputStream 實戰範例

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)。
  • 資源釋放:務必使用 try-with-resources 確保流關閉。
  • 大檔案處理:避免一次性讀入記憶體,採用固定大小緩衝區分塊處理。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved