很多初學者嘗試「一邊讀取文件內容、一邊加密寫回同一文件」,導致文件變空。原因在於:對同一文件同時開啟 FileInputStream 和 FileOutputStream,輸出流會立即截斷文件(長度歸零),輸入流隨後讀到的是空內容。
// 方案一:讀入內存處理後再寫回(小文件適用)
byte[] data = Files.readAllBytes(Paths.get("source.txt"));
byte[] encrypted = encrypt(data);
Files.write(Paths.get("source.txt"), encrypted);
// 方案二:寫入臨時文件,處理完替換原文件(大文件適用)
Path src = Paths.get("source.txt");
Path tmp = Files.createTempFile("enc-", ".tmp");
try (InputStream in = Files.newInputStream(src);
OutputStream out = Files.newOutputStream(tmp)) {
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) != -1) {
out.write(encrypt(buf, len)); // 加密塊寫入
}
}
Files.move(tmp, src, StandardCopyOption.REPLACE_EXISTING);
read → process → write(to another path)Files, Path) 代碼更簡潔安全推薦系統學習:Java IO 專題視頻