请编写程序,分别使用字节流和字符流拷贝一个文本文件。要求如下: 1.使用FileInputStream、FileOutputStream和FileReader、FileWriter分别进行拷贝。 2.使用字节流拷贝时,定义一个长度为1024的字节数组作为缓冲区;使用字符流进行拷贝时,使用BufferedReader和BufferedWriter包装流进行包装。
时间: 2023-12-06 21:45:13 浏览: 123
Java字符流和字节流对文件操作的区别
使用字节流拷贝:
```java
import java.io.*;
public class FileCopyByteStream {
public static void main(String[] args) {
String sourcePath = "source.txt";
String destPath = "dest.txt";
try {
FileInputStream fis = new FileInputStream(sourcePath);
FileOutputStream fos = new FileOutputStream(destPath);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
使用字符流拷贝:
```java
import java.io.*;
public class FileCopyCharStream {
public static void main(String[] args) {
String sourcePath = "source.txt";
String destPath = "dest.txt";
try {
FileReader fr = new FileReader(sourcePath);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(destPath);
BufferedWriter bw = new BufferedWriter(fw);
char[] buffer = new char[1024];
int len;
while ((len = br.read(buffer)) != -1) {
bw.write(buffer, 0, len);
}
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文