java怎么實(shí)現(xiàn)文件復(fù)制功能

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

Java可以通過使用FileInputStream和FileOutputStream來實(shí)現(xiàn)文件復(fù)制功能。例如,以下是一種實(shí)現(xiàn)文件復(fù)制的方法:

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("文件復(fù)制成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}

在上面的代碼中,你需要將 path_to_source_file 替換為源文件的路徑,將 path_to_destination_file 替換為目標(biāo)文件的路徑。程序會(huì)逐個(gè)讀取源文件中的字節(jié),并將其寫入目標(biāo)文件。最后,程序會(huì)關(guān)閉輸入流和輸出流,并打印出 “文件復(fù)制成功!” 的消息。

0