1. 编写一个程序,分别使用字节流和字符流拷贝一个文本文件。要求如下: (1)使用FileInputStream、FileOutputStreaem和FileReader、FileWriter分别进行拷贝。 (2)使用字节流拷贝时,定义一个1024长度的字节数组作为缓冲区;使用字符流拷贝
时间: 2024-02-21 19:01:10 浏览: 8
时,定义一个char数组作为缓冲区。
以下是使用字节流拷贝的代码示例:
```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStreamCopy {
public static void main(String[] args) {
String sourceFilePath = "source.txt";
String targetFilePath = "target.txt";
try (FileInputStream fis = new FileInputStream(sourceFilePath);
FileOutputStream fos = new FileOutputStream(targetFilePath)) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以下是使用字符流拷贝的代码示例:
```java
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CharacterStreamCopy {
public static void main(String[] args) {
String sourceFilePath = "source.txt";
String targetFilePath = "target.txt";
try (FileReader fr = new FileReader(sourceFilePath);
FileWriter fw = new FileWriter(targetFilePath)) {
char[] buffer = new char[1024];
int length;
while ((length = fr.read(buffer)) != -1) {
fw.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请注意,在使用完文件流后,需要及时关闭流以释放资源。使用try-with-resources语句可以自动关闭流,不需要手动关闭。