使用 FileInputStream 讀取、FileOutputStream 寫入,配合位元組緩衝區,可複製任意類型文件(文本、圖片、視頻等)。
package com.hp.io;
import java.io.*;
public class InputAndOutputFile {
public static void main(String[] args) {
File src = new File("f:/終於等到你.txt");
File dest = new File("f:/終於等到你了.txt");
try (FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest)) {
byte[] buffer = new byte[1024]; // 1KB 緩衝區
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
System.out.println("文件複製成功");
} catch (FileNotFoundException e) {
System.err.println("源文件不存在: " + e.getMessage());
} catch (IOException e) {
System.err.println("讀寫異常: " + e.getMessage());
}
}
}
fis.read(buffer) 返回實際讀取位元組數,-1 表示結束。fos.write(buffer, 0, len) 僅寫入有效數據,避免殘留舊數據。JDK 7+ 可使用 Files.copy(src.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING) 一行完成,底層利用零拷貝更高效。