Java
Java IO

Java IO 25 - FileWriter和FileReader详解

简介:流是一组有顺序的,有起点和终点的字节集合。是对设备文件间数据传输的总称和抽象。

1. FileReader简介

FileReader是用于读取字符流的类,继承于InputStreamReader。要读取原始字节流,可以考虑使用FileInputStream。
FileWriter是用于写入字符流的类,继承于OutputStreamWriter。要写入原始字节流,可以考虑使用FileOutputStream。

2. FileReader源码分析

下面是FileReader的源码,基于JDK 1.7.0_07:

  • package java.io;
  • public class FileReader extends InputStreamReader {
  • 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));
  • }
  • }

3. FileWriter源码分析

下面是FileWriter的源码,基于JDK 1.7.0_07:

  • package java.io;
  • public class FileWriter extends OutputStreamWriter {
  • 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));
  • }
  • }

4. FileWriter和FileReader示例

  • package com.coderap;
  • import org.junit.Test;
  • import java.io.FileReader;
  • import java.io.FileWriter;
  • import java.io.IOException;
  • public class FileWriterAndReaderTest {
  • @Test
  • public void testWriter() throws IOException {
  • FileWriter fileWriter = new FileWriter("file.data");
  • for (int i = 0; i < 26; i++) {
  • // 写入字符
  • fileWriter.write('a' + i);
  • if ("gntz".indexOf('a' + i) != -1) {
  • // 写入换行
  • fileWriter.write('\n');
  • } else if ("qw".indexOf('a' + i) != -1) {
  • // 写入空格
  • fileWriter.write(' ');
  • }
  • }
  • fileWriter.write("hello, 中国\n");
  • fileWriter.write("ABCDEFGH", 3, 4);
  • fileWriter.close();
  • }
  • @Test
  • public void testReader() throws IOException {
  • FileReader fileReader = new FileReader("file.data");
  • System.out.println("read: " + String.valueOf((char) fileReader.read()));
  • char[] chars = new char[4];
  • fileReader.read(chars);
  • System.out.println("read: " + new String(chars));
  • System.out.println("read remains: ");
  • int len;
  • while ((len = fileReader.read(chars)) != -1) {
  • System.out.print(new String(chars, 0, len));
  • }
  • }
  • }

先运行testWriter()方法,会创建一个file.data文件,内容如下:

  • abcdefg
  • hijklmn
  • opq rst
  • uvw xyz
  • hello, 中国
  • DEFG

先运行testReader()方法读取该文件的内容,结果如下:

  • read: a
  • read: bcde
  • read remains:
  • fg
  • hijklmn
  • opq rst
  • uvw xyz
  • hello, 中国
  • DEFG