| 維度 | 字節流 (InputStream/OutputStream) | 字符流 (Reader/Writer) |
|---|---|---|
| 最小單元 | 字節 (byte, 8 bits) | 字符 (char, 16 bits UTF-16) |
| 處理對象 | 所有二進制數據(圖片、視頻、音頻、二進制文件) | 文本文件(需指定編碼:UTF-8、GBK 等) |
| 核心抽象類 | InputStream / OutputStream | Reader / Writer |
| 轉換橋樑 | InputStreamReader / OutputStreamWriter(指定 Charset) | |
import java.io.*;
public class CharStreamDemo {
private static final File FILE = new File("D:/test.txt");
// 寫入:追加模式
public void write() {
try (PrintWriter pw = new PrintWriter(new FileWriter(FILE, true))) {
pw.write("測試輸出字符串到文件中");
} catch (IOException e) {
e.printStackTrace();
}
}
// 讀取:按行讀取並拼接
public String read() {
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(FILE))) {
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public static void main(String[] args) throws IOException {
CharStreamDemo demo = new CharStreamDemo();
demo.write();
System.out.println("文件內容:" + demo.read());
}
}
關鍵點:
• FileWriter(FILE, true) 第二參數 true 表示追加模式。
• try-with-resources 自動關閉流,避免資源洩漏。
• BufferedReader.readLine() 不包含換行符,業務需自行補充。
import java.io.*;
public class ByteStreamCopy {
public static void main(String[] args) {
File src = new File("D:/source.jpg");
File dest = new File("D:/target.jpg");
try (FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dest)) {
byte[] buffer = new byte[1024 * 4]; // 4KB 緩衝區
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len); // 關鍵:只寫實際讀取長度
}
System.out.println("複製完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}
關鍵點:
• 字節流不關心編碼,直接搬運二進制,適合非文本文件。
• out.write(buffer, 0, len) 必須指定偏移與長度,否則會寫入緩衝區殘留垃圾數據。
• 緩衝區大小 4KB~8KB 為經驗值,平衡系統調用次數與內存佔用。
「文本用字符,二進制用字節;不確定時,默認字節流最安全。」
new InputStreamReader(inputStream, StandardCharsets.UTF_8)。