1. 演示通过字节流实现文件复制功能。 提示:使用 FileInputStream 类/FileOutputStream 类。
时间: 2024-05-15 15:14:22 浏览: 10
好的,以下是一个通过字节流实现文件复制功能的Java代码示例:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
String sourceFilePath = "path/to/source/file";
String destFilePath = "path/to/destination/file";
try (FileInputStream fis = new FileInputStream(sourceFilePath);
FileOutputStream fos = new FileOutputStream(destFilePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
System.out.println("File copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们使用了Java的FileInputStream和FileOutputStream类,分别用于读取源文件和写入目标文件。在try-with-resources语句中,我们创建了这两个流对象,并使用一个缓冲区(byte数组)来读取和写入文件内容。while循环读取源文件的数据,并将其写入目标文件中,直到源文件的末尾。最后,我们输出一个简单的成功消息,或者在复制过程中出现异常时,输出异常堆栈跟踪信息。