FileReader和FileWriter进行字符读写的类,它们分别是InputStreamReader和InputStreamWriter的子类。

FileWriter

FileWriter的实现很简单,因为是一个OutputStreamWriter,所以只需要提供一个内部的OutputStream就能构造它,而这个OutputStream就是FileOutputStream:

  1. public FileWriter(String fileName) throws IOException {
  2. super(new FileOutputStream(fileName));
  3. }
  4. public FileWriter(String fileName, boolean append) throws IOException {
  5. super(new FileOutputStream(fileName, append));
  6. }
  7. public FileWriter(File file) throws IOException {
  8. super(new FileOutputStream(file));
  9. }
  10. public FileWriter(File file, boolean append) throws IOException {
  11. super(new FileOutputStream(file, append));
  12. }
  13. public FileWriter(FileDescriptor fd) {
  14. super(new FileOutputStream(fd));
  15. }

可以看到FileWriter的几个构造方法都是用一个FileOutputStream来构造的。FileWriter也只有构造方法,write方法已经在父类OutputStreamWriter中给出了实现。

FileReader

FileReader与FileWriter的实现基本一致,作为InputStreamReader的子类,它内部的InputStream是一个FileInputStream,构造方法也都是用FileInputStream来完成的:

  1. public FileReader(String fileName) throws FileNotFoundException {
  2. super(new FileInputStream(fileName));
  3. }
  4. public FileReader(File file) throws FileNotFoundException {
  5. super(new FileInputStream(file));
  6. }
  7. public FileReader(FileDescriptor fd) {
  8. super(new FileInputStream(fd));
  9. }

所以如果理解了InputStreamReader和OutputStreamWriter,FileReader和FileWriter的实现就很好理解了。