编写一个Java中的文件复制函数
发布时间:2023-06-29 18:49:52
文件复制是在计算机中非常常见的操作,下面是一个简单的Java文件复制函数的示例:
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
String sourceFilePath = "source.txt"; // 源文件路径
String destinationFilePath = "destination.txt"; // 目标文件路径
try {
// 创建源文件的输入流
FileInputStream sourceFileInputStream = new FileInputStream(sourceFilePath);
// 创建目标文件的输出流
FileOutputStream destinationFileOutputStream = new FileOutputStream(destinationFilePath);
// 缓冲区大小,可以按需更改
byte[] buffer = new byte[1024];
int length;
// 从源文件读取数据到缓冲区,并将缓冲区的数据写入目标文件,直到读取的长度为-1(文件结束)
while ((length = sourceFileInputStream.read(buffer)) > 0) {
destinationFileOutputStream.write(buffer, 0, length);
}
// 关闭输入输出流
sourceFileInputStream.close();
destinationFileOutputStream.close();
System.out.println("文件复制成功!");
} catch (IOException e) {
System.out.println("文件复制失败:" + e.getMessage());
}
}
}
上述代码中,我们首先定义了源文件路径和目标文件路径。然后,通过创建FileInputStream和FileOutputStream对象来创建输入和输出流。
我们创建了一个byte类型的缓冲区来保存从源文件读取的数据,指定缓冲区的大小为1024字节。
在一个while循环中,我们使用read()方法读取源文件中数据,并将读取的数据写入目标文件,直到读取的长度为-1,即文件结束。
最后,我们关闭输入和输出流,并打印出文件复制成功的消息。
请注意,此示例仅适用于文本文件的复制。如果要复制其他类型的文件(例如图片、视频、音频等),可以根据需要进行修改。
