Java 以 Unicode (UTF-16BE) 為內部編碼,檔案/網路傳輸需轉換為 UTF-8、GBK 等。核心 API:
String s = "好勤學習ABC";
byte[] utf8 = s.getBytes("UTF-8"); // 中文3字節,英文1字節
byte[] gbk = s.getBytes("GBK"); // 中文2字節,英文1字節
byte[] u16 = s.getBytes("UTF-16BE");// 中英文均2字節
// 解碼必須指定原編碼,否則產生亂碼
String str = new String(bytes, "UTF-8");
& 0xFF 技巧: Integer.toHexString(b & 0xFF) 將 signed byte 轉為無符號十六進制顯示,避免高位符號擴展干擾。
File f = new File("D:/data"); // 路徑分隔符建議用 File.separator 或 "/"
f.exists(); f.isDirectory(); f.isFile();
f.mkdir(); f.mkdirs(); f.delete();
f.getAbsolutePath(); f.getName(); f.getParent();
public static void listAll(File dir) {
if (!dir.exists() || !dir.isDirectory()) return;
for (File f : dir.listFiles()) {
if (f.isDirectory()) listAll(f);
else System.out.println(f.getAbsolutePath());
}
}
支援 `seek(pos)` 定位檔案指標,可讀可寫,適合斷點續傳、大檔案分片處理。
| 層級 | 輸入流 | 輸出流 | 特點 |
|---|---|---|---|
| 基礎節點流 | FileInputStream | FileOutputStream | 直接對接檔案,單位位元組 |
| 資料處理流 | DataInputStream | DataOutputStream | 按基本型別讀寫 |
| 緩衝流 | BufferedInputStream | BufferedOutputStream | 8KB緩衝,大幅提升效能 |
// 1. 單位元組:極慢
while ((c = in.read()) != -1) out.write(c);
// 2. 緩衝單位元組:尚可
while ((c = bis.read()) != -1) bos.write(c);
// 3. 緩衝批次讀寫:最快(推薦)
byte[] buf = new byte[8192];
int len;
while ((len = bis.read(buf)) != -1) bos.write(buf, 0, len);
實測 10MB 檔案:單位元組 ~20秒、緩衝單位元組 ~10秒、批次緩衝 < 100ms。
橋樑類:InputStreamReader / OutputStreamWriter 指定編碼轉換。
try (FileInputStream fis = new FileInputStream("utf8.txt");
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
FileOutputStream fos = new FileOutputStream("utf8_copy.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8")) {
char[] buf = new char[8192];
int len;
while ((len = isr.read(buf)) != -1) osw.write(buf, 0, len);
}
便利類:FileReader/FileWriter(預設平台編碼,跨平台慎用)、BufferedReader/BufferedWriter(按行讀寫)。
// 實作 Serializable
public class User implements Serializable { private String name; int age; }
// 序列化
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user.dat"))) {
oos.writeObject(new User("Tom", 25));
}
// 反序列化
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.dat"))) {
User u = (User) ois.readObject();
}
注意: serialVersionUID 明確宣告、transient 排除敏感/非持久化欄位、版本演進需相容規劃。
Path p = Paths.get("data.txt");
Files.readAllLines(p, StandardCharsets.UTF_8); // 一次讀全檔
Files.write(p, list, StandardCharsets.UTF_8); // 一次寫全檔
Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
Files.walkFileTree(root, new SimpleFileVisitor<>() { ... }); // 遍歷
NIO.2 為目前主流檔案操作推薦方式,API 更豐富、異步支援、串流式處理大檔更優雅。
掌握「編碼轉換、流層級裝飾模式、緩衝策略、序列化協議、NIO.2 現代 API」五大支柱,即可駕馭 Java 所有檔案/網路傳輸場景。實務上:文字用字元流+指定編碼,二進位用位元組流+緩衝批次,物件用序列化/JSON,現代專案優先 NIO.2。