、请设计编写一个程序,分别使用字节流和字符流拷贝一个文本文件。要求如下: (1)使用FilelnputStream.FileOutputStream 和 FileReader、FileWriter分别进行拷贝。 (2)使用字节流拷贝时,定义一个1024长度的字节数组作为缓冲区
时间: 2025-01-29 15:20:17 浏览: 34
为了满足您的需求,我会为您解释如何分别使用字节流和字符流来复制文本文件,并提供Java代码示例。首先,我们先了解字节流(如`FileInputStream`和`FileOutputStream`)用于处理原始数据,而字符流(如`BufferedReader`和`PrintWriter`)则用于读写字符。
**使用字节流(Byte Streams)**:
```java
import java.io.*;
public class ByteCopyExample {
public static void main(String[] args) throws IOException {
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
try (FileInputStream in = new FileInputStream(inputFile);
FileOutputStream out = new FileOutputStream(outputFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
// 使用循环逐块读取并写入
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
System.err.println("Error copying file: " + e.getMessage());
}
}
}
```
**使用字符流(Character Streams)**:
```java
import java.io.*;
public class CharCopyExample {
public static void main(String[] args) throws IOException {
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
PrintWriter writer = new PrintWriter(new FileWriter(outputFile))) {
String line;
// 使用循环逐行读取并写入
while ((line = reader.readLine()) != null) {
writer.println(line);
}
} catch (IOException e) {
System.err.println("Error copying file: " + e.getMessage());
}
}
}
```
阅读全文