錯誤代碼
byte[] buff = new byte[1024 * 4];
while (is.read(buff) != -1) {
os.write(buff); // ❌ 每次寫入整個緩衝區,含上次殘留數據
}
修正代碼
byte[] buff = new byte[1024 * 4];
int len;
while ((len = is.read(buff)) != -1) {
os.write(buff, 0, len); // ✅ 只寫入實際讀取的字節數
}
os.close(); // 先關輸出流,刷新緩衝區
is.close();
核心原理
InputStream.read(byte[]) 返回實際讀取字節數,末次讀取往往不滿緩衝區;
- 直接
write(buff) 會將緩衝區剩餘舊數據一起寫入,導致文件變大、內容重複;
write(buff, 0, len) 精確寫入有效數據。
最佳實踐
- 使用
try-with-resources (Java 7+) 自動關閉流;
- 大文件考慮
Files.copy(inputStream, path, StandardCopyOption.REPLACE_EXISTING) (Java 7+);
- 網絡流設置連接/讀取超時:
conn.setConnectTimeout(5000); conn.setReadTimeout(10000);。