FileReader和FileWriter进行字符读写的类,它们分别是InputStreamReader和InputStreamWriter的子类。
FileWriter
FileWriter的实现很简单,因为是一个OutputStreamWriter,所以只需要提供一个内部的OutputStream就能构造它,而这个OutputStream就是FileOutputStream:
public FileWriter(String fileName) throws IOException {
super(new FileOutputStream(fileName));
}
public FileWriter(String fileName, boolean append) throws IOException {
super(new FileOutputStream(fileName, append));
}
public FileWriter(File file) throws IOException {
super(new FileOutputStream(file));
}
public FileWriter(File file, boolean append) throws IOException {
super(new FileOutputStream(file, append));
}
public FileWriter(FileDescriptor fd) {
super(new FileOutputStream(fd));
}
可以看到FileWriter的几个构造方法都是用一个FileOutputStream来构造的。FileWriter也只有构造方法,write方法已经在父类OutputStreamWriter中给出了实现。
FileReader
FileReader与FileWriter的实现基本一致,作为InputStreamReader的子类,它内部的InputStream是一个FileInputStream,构造方法也都是用FileInputStream来完成的:
public FileReader(String fileName) throws FileNotFoundException {
super(new FileInputStream(fileName));
}
public FileReader(File file) throws FileNotFoundException {
super(new FileInputStream(file));
}
public FileReader(FileDescriptor fd) {
super(new FileInputStream(fd));
}
所以如果理解了InputStreamReader和OutputStreamWriter,FileReader和FileWriter的实现就很好理解了。