分别使用字节流和字符流拷贝一个文本文件
时间: 2023-04-18 17:03:56 浏览: 140
使用字节流拷贝文本文件:
1. 创建一个 FileInputStream 对象,用于读取源文件。
2. 创建一个 FileOutputStream 对象,用于写入目标文件。
3. 定义一个 byte 数组,用于存储读取的数据。
4. 循环读取源文件中的数据,将读取到的数据存储到 byte 数组中。
5. 将 byte 数组中的数据写入目标文件中。
6. 关闭 FileInputStream 和 FileOutputStream 对象。
示例代码:
```
import java.io.*;
public class ByteStreamCopy {
public static void main(String[] args) {
String srcFilePath = "source.txt";
String destFilePath = "target.txt";
try (FileInputStream fis = new FileInputStream(srcFilePath);
FileOutputStream fos = new FileOutputStream(destFilePath)) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
使用字符流拷贝文本文件:
1. 创建一个 FileReader 对象,用于读取源文件。
2. 创建一个 FileWriter 对象,用于写入目标文件。
3. 定义一个 char 数组,用于存储读取的数据。
4. 循环读取源文件中的数据,将读取到的数据存储到 char 数组中。
5. 将 char 数组中的数据写入目标文件中。
6. 关闭 FileReader 和 FileWriter 对象。
示例代码:
```
import java.io.*;
public class CharacterStreamCopy {
public static void main(String[] args) {
String srcFilePath = "source.txt";
String destFilePath = "target.txt";
try (FileReader fr = new FileReader(srcFilePath);
FileWriter fw = new FileWriter(destFilePath)) {
char[] buffer = new char[1024];
int length;
while ((length = fr.read(buffer)) > 0) {
fw.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```