1. 编写一个程序,分别使用字节流和字符流拷贝一个文本文件。要求如下: (1)使用FileInputStream、FileOutputStreaem和FileReader、FileWriter分别进行拷贝。 (2)使用字节流拷贝时,定义一个1024长度的字节数组作为缓冲区,使用字符流拷贝。
时间: 2024-02-09 13:13:29 浏览: 33
好的,下面是使用字节流和字符流分别拷贝一个文本文件的代码示例:
1. 使用字节流拷贝文本文件
```java
import java.io.*;
public class FileCopyByByteStream {
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)) > 0) {
fos.write(buffer, 0, length);
}
fis.close();
fos.close();
System.out.println("File copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. 使用字符流拷贝文本文件
```java
import java.io.*;
public class FileCopyByCharStream {
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)) > 0) {
fw.write(buffer, 0, length);
}
fr.close();
fw.close();
System.out.println("File copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意,在使用字符流拷贝文本文件时,需要使用`FileReader`和`FileWriter`,而不是`FileInputStream`和`FileOutputStream`。同时,缓冲区的类型也需要从字节数组改成字符数组。