1. 编写一个程序,分别使用字节流和字符流拷贝一个文本文件。要求如下:(1)使用FileInputStream、FileOutputStreaem和FileReader、FileWriter分别进行拷贝。(2)使用字节流拷贝时,定义一个1024长度的字节数组作为缓冲区,使用字符流拷贝。
时间: 2024-02-09 18:12:31 浏览: 30
好的,下面是程序的代码实现:
使用字节流拷贝:
```java
import java.io.*;
public class ByteStreamCopyFile {
public static void main(String[] args) {
String sourceFilePath = "source.txt";
String destFilePath = "dest.txt";
byte[] buffer = new byte[1024];
try (FileInputStream fis = new FileInputStream(sourceFilePath);
FileOutputStream fos = new FileOutputStream(destFilePath)) {
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
使用字符流拷贝:
```java
import java.io.*;
public class CharacterStreamCopyFile {
public static void main(String[] args) {
String sourceFilePath = "source.txt";
String destFilePath = "dest.txt";
try (FileReader fr = new FileReader(sourceFilePath);
FileWriter fw = new FileWriter(destFilePath)) {
char[] buffer = new char[1024];
int len;
while ((len = fr.read(buffer)) != -1) {
fw.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
其中,字节流拷贝使用FileInputStream和FileOutputStream来读取和写入文件,同时定义了一个1024长度的字节数组作为缓冲区,以提高读写效率;字符流拷贝使用FileReader和FileWriter来读取和写入文件,也定义了一个1024长度的字符数组作为缓冲区。