使用BufferedInputStream和BufferedOutputStream编写程序,实现文件的复制。(如将D 盘m.txt文件的内容复制到D盘n.txt文件中
时间: 2025-01-05 10:40:40 浏览: 7
当你需要在Java中使用`BufferedInputStream`和`BufferedOutputStream`来复制文件时,你可以按照以下步骤操作:
1. 首先,创建一个`BufferedReader`和一个`BufferedWriter`对象,分别用于读取输入流和写入输出流。这两个类都是对标准的`InputStreamReader`和`OutputStreamWriter`进行了缓冲处理。
```java
FileInputStream fis = new FileInputStream("D:\\m.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8));
FileOutputStream fos = new FileOutputStream("D:\\n.txt");
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8));
```
2. 使用循环逐行读取输入文件,并将其写入输出文件。这通常涉及到一行接一行地从`BufferedReader`读取,然后存储到`BufferedWriter`中。
```java
String line;
while ((line = in.readLine()) != null) {
out.write(line);
out.newLine(); // 每写一行后换行
}
```
3. 最后关闭两个流,释放资源。
```java
in.close();
out.close();
fis.close();
fos.close();
```
完整的代码示例如下:
```java
import java.io.*;
public class FileCopyExample {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("D:\\m.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8));
FileOutputStream fos = new FileOutputStream("D:\\n.txt");
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
out.write(line);
out.newLine();
}
in.close();
out.close();
fis.close();
fos.close();
System.out.println("File copy completed successfully.");
} catch (IOException e) {
System.err.println("Error occurred during file copy: " + e.getMessage());
}
}
}
```
阅读全文