天天看点

Reader、Writer 字符输入输出流

Reader 字符输入流

源码剖析:

  • 继承关系:
abstract class Reader implements Readable, Closeable
 //抽象类
 //可以读取,可以自动关闭
           
  • 构造方法:
//有参数、无参数
 protected Reader() {
        this.lock = this;
    }

    /**
     * Creates a new character-stream reader whose critical sections will
     * synchronize on the given object.
     *
     * @param lock  The Object to synchronize on.
     */
    protected Reader(Object lock) {
        if (lock == null) {
            throw new NullPointerException();
        }
        this.lock = lock;
    }
           
  • 基本方法:
int read(java.nio.CharBuffer target) 试图将字符读入指定的字符缓冲区
int read() 读取单个字符,读操作结束的返回值-1,返回值就是字符对应的ASCII码的数字
int read(char cbuf[]) 将字符读入数组,读操作结束的返回值-1,数据读取到char []数组中,返回值表示读取有效数据个数
int read(char cbuf[], int off, int len) 将字符读入数组的某一部分,读操作结束的返回值-1,数据读取到char []数组中,可以指定读取数据的起始和大小,返回值表示读取有效数据个数
long skip(long n) 跳过指定长度的字符
boolean ready() 判断是否准备读取此流
boolean markSupported() 判断此流是否支持 mark() 操作
void mark(int readAheadLimit) 标记流中的当前位置
void reset() 重置该流
void close() 关闭该流并释放与之关联的所有资源
  • 读操作具体操作步骤:

1.打开字符读操作流,可能会抛出异常FileNotFoundException;

FileReader fileReader = new FileReader(path);

2.读操作,可能会抛出IOException异常;

fileReader.read();

3.关闭流。

fileReader.close();

public class InputOutStreamDemo {
	public static void read(String path){
        try {
            FileReader fileReader = new FileReader(path);//存储cabhellolucy

            int read = fileReader.read();//读取单个字符
            System.out.println(read);//output:99

            char[] chars = new char[100];
            System.out.println(fileReader.read(chars));//output:11

            fileReader.read(chars,0,10);

            fileReader.mark(2);
            fileReader.markSupported();
            fileReader.reset();

            fileReader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        String path = "C:\\Users\\a\\Desktop\\L\\inputtest.txt";//空文件
        read(path);
    }
}
           

Writer字符输出流

源码剖析:

  • 继承关系:
abstract class Writer implements Appendable, Closeable, Flushable
//抽象类
//实现可追加,可自动关闭,可刷新缓存
           
  • 基本属性和构造方法:
/**
     * Temporary buffer used to hold writes of strings and single characters
     * 缓冲区被用来存储写入字符串和单个字符
     */
    private char[] writeBuffer;

    /**
     * Size of writeBuffer, must be >= 1,写入缓冲区的大小
     */
    private final int writeBufferSize = 1024;

    /**
     * The object used to synchronize operations on this stream.  For
     * efficiency, a character-stream object may use an object other than
     * itself to protect critical sections.  A subclass should therefore use
     * the object in this field rather than <tt>this</tt> or a synchronized
     * method.用于同步针对此流的操作的对象。
     */
    protected Object lock;
    
    protected Writer() {
        this.lock = this;
    }
    protected Writer(Object lock) {
        if (lock == null) {
            throw new NullPointerException();
        }
        this.lock = lock;
    }
           
  • 基本方法:
void write(int c) 写入单个字符
void write(char cbuf[]) 写入字符数组
void write(char cbuf[], int off, int len) 写入字符数组的某一部分,自定义起始和长度
void write(String str) 写入字符串
void write(String str, int off, int len) 直接写入字符串,自定义写入字符串子集
Writer append(CharSequence csq) 将指定字符序列添加到此 writer
Writer append(CharSequence csq, int start, int end) 将指定字符序列的子序列添加到此 writer.Appendable
Writer append(char c) 将指定字符添加到此 writer
void flush() 刷新该流的缓冲
void close() 关闭此流,但要先刷新它
  • 读操作具体步骤:

1.打开字符写操作流,可能会抛出异常IOException;

FileWriter writer = new FileWriter(path,true);

2.写操作,可能会抛出IOException异常;

fileWriter.write(99);

3.关闭流,可能会抛出IOException异常。

fileWriter.close();

public class InputOutStreamDemo {
	public static void write(String path){
        try {
            FileWriter fileWriter = new FileWriter(path);//空文件,构造函数中默认append为false


            fileWriter.write('c');
            fileWriter.write("hello");
            char[] chars = {'a','b','c'};
            fileWriter.write(chars);//chelloabc

            fileWriter.write("happy",0,3);//写入hap
            fileWriter.write(chars,0,2);//写入ab

            //保证追加数据的流必须和前期写入的流是同一个打开的流实例
            fileWriter.append("明天见");//覆盖写入,chelloabchapab明天见


            /*FileWriter fileWriter1 = new FileWriter(path,true);//追加写入,将append置为true
            //fileWriter1.write("Yes,It is me");
            fileWriter1.append("youyic",0,2);//Yes,It is meyo
            fileWriter1.close();*/
            fileWriter.flush();
            fileWriter.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        String path = "C:\\Users\\a\\Desktop\\L\\inputtest.txt";//空文件
        write(path);
    }
}
           

注意:

构造函数 FileWriter(String fileName, boolean append) 
第二个参数表示数据是否追加 true:追加的形式写入 false:覆盖原内容的形式写入 ,默认是false
 * @param append    boolean if <code>true</code>, then data will be written
 *                  to the end of the file rather than the beginning.
           

注意: 在使用方法时注意会抛出IOException异常。