📅  最后修改于: 2023-12-03 14:43:03.417000             🧑  作者: Mango
在Java中,我们可以使用java.io
包中的FileInputStream
和FileOutputStream
类来复制文件。以下是一个简单的示例程序来演示如何使用Java程序复制文件。
File sourceFile = new File("source.txt");
File destinationFile = new File("destination.txt");
InputStream inputStream = new FileInputStream(sourceFile);
OutputStream outputStream = new FileOutputStream(destinationFile);
使用缓冲数组可以提高复制速度和效率:
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
示例代码如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class FileCopyDemo {
public static void main(String[] args) throws Exception {
File sourceFile = new File("source.txt");
File destinationFile = new File("destination.txt");
InputStream inputStream = new FileInputStream(sourceFile);
OutputStream outputStream = new FileOutputStream(destinationFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
System.out.println("文件已复制");
}
}
使用Java程序复制文件非常简单,只需要使用FileInputStream
和FileOutputStream
类来读取和写入数据就可以了。记得在复制完成后关闭流以释放资源。