使用字节输入输出流完成文件的复制
时间: 2024-03-27 21:35:55 浏览: 12
好的,以下是使用字节输入输出流完成文件复制的Java代码示例:
```java
import java.io.*;
public class FileCopyExample {
public static void main(String[] args) {
String sourceFilePath = "path/to/source/file";
String destFilePath = "path/to/destination/file";
try (InputStream inputStream = new FileInputStream(new File(sourceFilePath));
OutputStream outputStream = new FileOutputStream(new File(destFilePath))) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
System.out.println("File copied successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们使用了字节输入输出流来读取和写入文件。首先,我们打开了输入流,读取源文件,并打开了输出流,将数据写入目标文件。然后,我们定义了一个缓冲区,并使用 while 循环读取输入流中的字节,将其写入输出流中。最后,我们关闭了输入输出流,并在控制台上打印了一条成功复制的消息。