1. 编写一个程序,分别使用字节流和字符流拷贝一个文本文件。要求如下: (1)使用FileInputStream、FileOutputStreaem和FileReader、FileWriter分别进行拷贝。 (2)使用字节流拷贝时,定义一个1024长度的字节数组作为缓冲区;使用字符流拷贝
时间: 2024-02-20 18:59:37 浏览: 175
好的,我知道了。以下是使用字节流和字符流分别拷贝一个文本文件的程序代码:
使用字节流拷贝:
```java
import java.io.*;
public class ByteStreamCopy {
public static void main(String[] args) {
String srcFilePath = "source.txt";
String destFilePath = "destination.txt";
try {
FileInputStream fis = new FileInputStream(srcFilePath);
FileOutputStream fos = new FileOutputStream(destFilePath);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
fis.close();
fos.close();
System.out.println("File copied successfully using byte stream!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
使用字符流拷贝:
```java
import java.io.*;
public class CharacterStreamCopy {
public static void main(String[] args) {
String srcFilePath = "source.txt";
String destFilePath = "destination.txt";
try {
FileReader fr = new FileReader(srcFilePath);
FileWriter fw = new FileWriter(destFilePath);
char[] buffer = new char[1024];
int length;
while ((length = fr.read(buffer)) != -1) {
fw.write(buffer, 0, length);
}
fr.close();
fw.close();
System.out.println("File copied successfully using character stream!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意:在使用字符流进行拷贝时,文件中的内容会被当做字符来处理,因此如果文件中包含非文本内容,可能会出现乱码或者不正确的拷贝结果。
阅读全文
相关推荐


















