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
替换为目标文件的路径。程序会逐个读取源文件中的字节,并将其写入目标文件。最后,程序会关闭输入流和输出流,并打印出 “文件复制成功!” 的消息。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
相关推荐:java如何实现文件复制功能