FileReader和FileOutputStream
时间: 2024-05-03 18:15:04 浏览: 7
FileReader和FileOutputStream是Java中用于文件读取和文件写入的类。
1. FileReader(文件读取):
FileReader类用于读取字符文件。它继承自InputStreamReader类,可以读取字符流或字节流,并将其转换为字符流。使用FileReader可以逐个字符地读取文本文件的内容。
2. FileOutputStream(文件写入):
FileOutputStream类用于将数据写入文件。它继承自OutputStream类,可以写入字节流或字符流。使用FileOutputStream可以将数据以字节的形式写入到文件中。
相关问题
FileReader FileOutputStream FileInputStream
这三个都是Java中用于文件读写的类。其中FileReader是用于读取字符文件的,FileInputStream和FileOutputStream则是用于读写字节文件的。
FileReader继承自InputStreamReader,它的read()方法会读取一个字符并返回,如果已经到达文件末尾,则返回-1。FileReader还有一个read(char[] cbuf, int off, int len)方法,可以一次读取多个字符到指定的字符数组中。
FileInputStream和FileOutputStream则是用于读写字节文件的。FileInputStream的read()方法会读取一个字节并返回,如果已经到达文件末尾,则返回-1。FileOutputStream的write()方法可以将一个字节或者一个字节数组写入到文件中。
编写一个程序,分别使用字节流和字符流复制一个文件。要求如下: 1、使用FileInputStream、FileOutputStream和FileReader、FileWriter分别进行复制 2、使用字节流复制时,定义一个长度为1024的字节数组作为缓冲区。
好的,下面是使用字节流和字符流分别复制文件的示例代码:
使用字节流复制文件:
```java
import java.io.*;
public class ByteStreamCopy {
public static void main(String[] args) {
String srcFile = "source.txt";
String destFile = "destination.txt";
try (FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
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 srcFile = "source.txt";
String destFile = "destination.txt";
try (FileReader reader = new FileReader(srcFile);
FileWriter writer = new FileWriter(destFile)) {
char[] buffer = new char[1024];
int length;
while ((length = reader.read(buffer)) > 0) {
writer.write(buffer, 0, length);
}
System.out.println("File copied successfully using character stream.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上两个示例代码中,都使用了try-with-resources语句来自动关闭文件流。在使用字节流复制文件时,定义了一个长度为1024的字节数组作为缓冲区,每次读取文件时将数据读入缓冲区,然后再将缓冲区中的数据写入目标文件。在使用字符流复制文件时,也定义了一个长度为1024的字符数组作为缓冲区,使用reader.read(buffer)方法读取文件数据,然后使用writer.write(buffer)方法将数据写入目标文件。