需求:將 D:/good boy.txt 複製到 C:/myFile.txt。
while ((fis.read()) != -1) { // 錯誤:這裡已消費一個位元組
fis.read(words); // 從第二個位元組開始讀入數組
fos.write(words, 0, words.length); // 寫入整個數組長度,而非實際讀取長度
}
fis.read() 在判斷條件中單獨調用,消費了流中的第一個位元組,且未保存。fis.read(words) 從第二個位元組開始讀取,導致數據缺失首字節。fos.write(words, 0, words.length) 使用數組總長度而非實際讀取長度 len,會將數組殘留的舊數據或零值寫入目標文件。FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("D:/good boy.txt");
fos = new FileOutputStream("C:/myFile.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) { // 讀取並判斷在同一表達式
fos.write(buffer, 0, len); // 按實際讀取長度寫入
}
fos.flush();
System.out.println("複製完成");
} catch (IOException e) {
e.printStackTrace();
} finally {
try { if (fis != null) fis.close(); } catch (IOException ignore) {}
try { if (fos != null) fos.close(); } catch (IOException ignore) {}
}
(len = fis.read(buf)) != -1,確保每個位元組只被讀取一次並參與判斷。fos.write(buf, 0, len),避免寫入垃圾數據。