1、 编写一个程序,分别使用字节流和字符流拷贝一个文本文件。 提示: 需要在当前路径下,先建立一个src.txt的文本文件,内容如下图所示,然后通过文件字节输出流FileOutputStream在当前路径下建立dest1.txt文本文件,并且写入数据。通过文件字符输出流FileWriter在当前路径下建立dest2.txt文本文件,并且写入数据。 1) 使用FileInputStream、FileOutputStream和FileReader、FileWriter分别进行拷贝。 2) 使用字节流拷贝时,定义一个1024长度的字节数组作为缓冲区,使用字符流拷贝,使用BufferedReader和BufferedWriter包装流进行包装
时间: 2024-02-24 18:57:21 浏览: 123
好的,以下是使用字节流和字符流分别拷贝文本文件的代码示例:
1. 使用字节流拷贝文件
```java
import java.io.*;
public class ByteStreamCopy {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("src.txt");
FileOutputStream fos = new FileOutputStream("dest1.txt");
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fis.close();
fos.close();
System.out.println("拷贝完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. 使用字符流拷贝文件
```java
import java.io.*;
public class CharacterStreamCopy {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("src.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("dest2.txt");
BufferedWriter bw = new BufferedWriter(fw);
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
br.close();
bw.close();
System.out.println("拷贝完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意:以上代码示例仅供参考,实际应用中需要对异常进行处理。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)