溫馨提示×

java怎么實現文件復制功能

小億
110
2023-08-11 19:50:40
欄目: 編程語言

Java可以通過使用FileInputStream和FileOutputStream來實現文件復制功能。例如,以下是一種實現文件復制的方法:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopy {
public static void main(String[] args) {
String sourcePath = "path_to_source_file";
String destinationPath = "path_to_destination_file";
try {
FileInputStream fis = new FileInputStream(sourcePath);
FileOutputStream fos = new FileOutputStream(destinationPath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
fis.close();
fos.close();
System.out.println("文件復制成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}

在上面的代碼中,你需要將 path_to_source_file 替換為源文件的路徑,將 path_to_destination_file 替換為目標文件的路徑。程序會逐個讀取源文件中的字節,并將其寫入目標文件。最后,程序會關閉輸入流和輸出流,并打印出 “文件復制成功!” 的消息。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女