while (is.read(buff) != -1) {
os.write(buff); // 寫入整個緩衝區,包含上次殘留數據
}
read(buff) 返回實際讀取字節數 len,末尾可能不滿緩衝區。直接 write(buff) 會寫入殘留舊數據,導致文件變大、內容錯誤。
byte[] buff = new byte[4096];
int len;
while ((len = is.read(buff)) != -1) {
os.write(buff, 0, len); // 關鍵:只寫入實際讀取的長度
}
os.close(); // 先關輸出流刷新緩衝區
is.close();
try-with-resources (Java 7+) 自動關閉流。Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING) (Java 7+)。Content-Length 預分配空間或驗證完整性。