| 維度 | 分類 | 基本類 | 處理單位 | 典型用途 |
|---|---|---|---|---|
| 按數據類型 | 字節流 | InputStream / OutputStream | 8位字節 | 圖片、視頻、二進制、網絡傳輸 |
| 字符流 | Reader / Writer | 16位字符 (UTF-16) | 文本文件、字符串處理、控制台 | |
| 按流向 | 輸入流 | InputStream / Reader | - | 讀取數據源 |
| 輸出流 | OutputStream / Writer | - | 寫入目標 |
File.separator、File.pathSeparatorimport java.io.*;
public class FileTest {
public static void main(String[] args) {
try {
// 1. 鍵盤輸入流 (標準輸入)
FileInputStream fis = new FileInputStream(FileDescriptor.in);
// 2. 文件輸出流
FileOutputStream fos = new FileOutputStream("d:\\myfile.txt");
System.out.println("請輸入字符串,以 # 結束:");
int ch;
while ((ch = fis.read()) != '#') { // 讀取單字節
fos.write(ch); // 寫入單字節
}
fis.close();
fos.close();
// 3. 文件輸入流讀回
FileInputStream fi = new FileInputStream("d:\\myfile.txt");
// 4. 控制台輸出流 (標準輸出)
FileOutputStream fo = new FileOutputStream(FileDescriptor.out);
int data;
while (fi.available() > 0) { // 可用字節數
data = fi.read();
fo.write(data);
}
fi.close();
fo.close();
} catch (FileNotFoundException e) {
System.out.println("文件未找到:" + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
}
}
關鍵點:FileDescriptor.in/out 代表標準輸入輸出,available() 估算可讀字節,單字節讀寫效率低,教學用。
import java.io.*;
public class ImageFileTest {
public static void main(String[] args) throws IOException {
FileInputStream fi = new FileInputStream("d:\\scenery.jpg");
FileOutputStream fo = new FileOutputStream("d:\\copyScenery.jpg");
// 一次性讀入內存(僅適合小文件)
byte[] buffer = new byte[fi.available()];
fi.read(buffer); // 讀滿數組
fo.write(buffer); // 寫入數組
System.out.println("文件已複製並重命名");
fi.close();
fo.close();
}
}
改進方向:大文件必須分塊讀寫(如 4KB/8KB 緩衝區),避免 OOM。
// 字節流 → 字符流 (指定編碼)
InputStreamReader isr = new InputStreamReader(new FileInputStream("data.txt"), "UTF-8");
BufferedReader br = new BufferedReader(isr);
// 字符流 → 字節流 (指定編碼)
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("out.txt"), "UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
核心認知:InputStreamReader/OutputStreamWriter 是編碼轉換器,解決字節與字符邊界問題。
// 自動關閉資源,異常安全
try (FileInputStream fis = new FileInputStream("in.txt");
FileOutputStream fos = new FileOutputStream("out.txt")) {
byte[] buf = new byte[8192];
int len;
while ((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
} // 編譯器自動生成 finally 關閉代碼
Java IO 基石在於:流的單向性、字節/字符二元分類、裝飾者模式組合功能。掌握 File 與流的分工、字節字符轉換橋樑、緩衝區大小選擇、try-with-resources 资源安全,即可應對 90% 文件處理場景。