用Java实现文件复制
时间: 2024-11-25 09:31:30 浏览: 22
在Java中,我们可以使用`java.io`包下的`FileInputStream`、`FileOutputStream`以及`BufferedInputStream`和`BufferedOutputStream`类来实现文件的复制。下面是一个简单的示例,展示了如何将一个源文件复制到另一个目标文件:
```java
import java.io.*;
public class FileCopyExample {
public static void main(String[] args) {
try {
// 源文件路径和目标文件路径
String src = "src/file.txt";
String dest = "dest/copy_of_file.txt";
// 创建输入流和输出流
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dest);
// 创建缓冲流
BufferedInputStream buffIn = new BufferedInputStream(in);
BufferedOutputStream buffOut = new BufferedOutputStream(out);
// 读取并写入数据
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = buffIn.read(buffer)) != -1) {
buffOut.write(buffer, 0, bytesRead);
}
// 关闭所有流
buffIn.close();
buffOut.close();
in.close();
out.close();
System.out.println("文件复制完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们首先创建了输入和输出文件流,然后通过缓冲流提高性能。接着读取源文件的字节,并逐块写入到目标文件。最后别忘了关闭所有的流以释放资源。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)