Java I/O 採用流模型:資料像水流一樣在來源與目的地之間傳輸。核心在於裝飾者模式,透過層層包裝賦予額外功能 (緩衝、轉碼、物件序列化等)。
| 維度 | 位元組流 | 字元流 |
|---|---|---|
| 基本單位 | Byte (8 bits) | Char (16 bits, UTF-16) |
| 抽象基類 | `InputStream` / `OutputStream` | `Reader` / `Writer` |
| 適用場景 | 圖片、影音、二進位檔、網路傳輸 | 文字檔、XML、JSON、字串處理 |
| 轉換橋樑 | `InputStreamReader` / `OutputStreamWriter` (指定 Charset) | |
// 逐行讀取,自動關閉資源
public List<String> readLines(Path path, Charset charset) throws IOException {
try (BufferedReader reader = Files.newBufferedReader(path, charset)) {
return reader.lines().collect(Collectors.toList()); // Java 8 Stream API
}
}
// 或手動處理
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream("data.txt"), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
process(line);
}
}
public void writeLines(Path path, List<String> lines, Charset charset) throws IOException {
try (BufferedWriter writer = Files.newBufferedWriter(path, charset,
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
for (String line : lines) {
writer.write(line);
writer.newLine(); // 平台無關換行
}
}
}
// 內部使用零拷貝 或直接緩衝區傳輸,極快
Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
// 手動緩衝複製 (傳統 IO)
try (InputStream in = new BufferedInputStream(new FileInputStream(src));
OutputStream out = new BufferedOutputStream(new FileOutputStream(dest))) {
byte[] buffer = new byte[8192];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
}
// 簡單解析用 Scanner
try (Scanner sc = new Scanner(System.in, StandardCharsets.UTF_8.name())) {
System.out.print("請輸入長方形長: ");
double len = sc.nextDouble();
System.out.print("請輸入寬: ");
double wid = sc.nextDouble();
System.out.printf("面積: %.2f%n", len * wid);
}
// 高效能/大量資料用 BufferedReader
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
System.out.print("輸入: ");
String input = br.readLine();
}