JAVA基础 | IO之BufferedReader与BufferedWriter

本文介绍了BufferedReader和BufferedWriter在Java中的关键特性,包括它们用于高效字符输入输出的缓存机制、构造方法、涉及变量和核心方法,以及如何通过实例展示其在实际编程中的应用。

IO系列文章目录



前言

当我们明确了要操作的是数据是字符,Reader与Writer就是称为我们一个很好的选择,如果我们需要高效性,引入缓存区,那我们就可以选择BufferedReader与BufferedWriter,接下来我们来看一下他们的区别与使用


提示:以下是本篇文章正文内容

一、BufferedWriter

1. 简介

Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

将文本写入字符输出流,缓存字符以便有效的写入单个字符,数组和字符串

2. 构造方法

 /**
     * Creates a buffered character-output stream that uses a default-sized
     * output buffer.
     * 创建一个缓存字符输出流,使用默认大小的输出。
     * @param  out  A Writer
     */
    public BufferedWriter(Writer out) {
        this(out, defaultCharBufferSize);
    }
    
    /**
     * Creates a new buffered character-output stream that uses an output
     * buffer of the given size.
     *  创建一个新的缓存字符输出流
     * @param  out  A Writer
     * @param  sz   Output-buffer size, a positive integer
     *
     * @exception  IllegalArgumentException  If {@code sz <= 0}
     */
    public BufferedWriter(Writer out, int sz) {
        super(out);
        if (sz <= 0)
            throw new IllegalArgumentException("Buffer size <= 0");
        this.out = out;
        cb = new char[sz];
        nChars = sz;
        nextChar = 0;

        lineSeparator = java.security.AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction("line.separator"));
    }

3. 涉及变量

private Writer out;
//传入的字符数组
private char cb[];
private int nChars, nextChar;
//默认输出大小
private static int defaultCharBufferSize = 8192;
//行分隔符字符串
private String lineSeparator;

4. 涉及方法

 /** Checks to make sure that the stream has not been closed 
    检查确认流已经被关闭
    */
    private void ensureOpen() throws IOException {
        if (out == null)
            throw new IOException("Stream closed");
    }
        
    
    /**
     * Flushes the output buffer to the underlying character stream, without
     * flushing the stream itself.  This method is non-private only so that it
     * may be invoked by PrintStream.
     * 将输出缓冲区刷新到底层字符流,无需冲洗洗* 流本身。这个方法是非私有的可由PrintStrea* m调用
     */
    void flushBuffer() throws IOException {
        synchronized (lock) {
            ensureOpen();
            if (nextChar == 0)
                return;
            out.write(cb, 0, nextChar);
            nextChar = 0;
        }
    }
    
    /**
     * Writes a single character.
     * 写入单个字符
     * @exception  IOException  If an I/O error occurs
     */
    public void write(int c) throws IOException {
        synchronized (lock) {
            ensureOpen();
            if (nextChar >= nChars)
                flushBuffer();
            cb[nextChar++] = (char) c;
        }
    }
    
    /**
     * Writes a portion of an array of characters.
     * 写入一个数组
     */
    public void write(char cbuf[], int off, int len) throws IOException {
        synchronized (lock) {
            ensureOpen();
            if ((off < 0) || (off > cbuf.length) || (len < 0) ||
                ((off + len) > cbuf.length) || ((off + len) < 0)) {
                throw new IndexOutOfBoundsException();
            } else if (len == 0) {
                return;
            }

            if (len >= nChars) {
                /* If the request length exceeds the size of the output buffer,
                   flush the buffer and then write the data directly.  In this
                   way buffered streams will cascade harmlessly. */
                flushBuffer();
                out.write(cbuf, off, len);
                return;
            }

            int b = off, t = off + len;
            while (b < t) {
                int d = min(nChars - nextChar, t - b);
                System.arraycopy(cbuf, b, cb, nextChar, d);
                b += d;
                nextChar += d;
                if (nextChar >= nChars)
                    flushBuffer();
            }
        }
    }
    
    /**
     * Writes a portion of a String.
     * 写入一个字符串
     */
    public void write(String s, int off, int len) throws IOException {
        synchronized (lock) {
            ensureOpen();

            int b = off, t = off + len;
            while (b < t) {
                int d = min(nChars - nextChar, t - b);
                s.getChars(b, b + d, cb, nextChar);
                b += d;
                nextChar += d;
                if (nextChar >= nChars)
                    flushBuffer();
            }
        }
    }
    /**
     * 换行符
     **/
    public void newLine() throws IOException {
        write(lineSeparator);
    }
    
    /**
     * Flushes the stream.
     * 刷新流
     * @exception  IOException  If an I/O error occurs
     */
    public void flush() throws IOException {
        synchronized (lock) {
            flushBuffer();
            out.flush();
        }
    }
    
    public void close() throws IOException {
        synchronized (lock) {
            if (out == null) {
                return;
            }
            try (Writer w = out) {
                flushBuffer();
            } finally {
                out = null;
                cb = null;
            }
        }
    }

二、 BufferedReader

1. 简介

Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

将字符输出流中读取文本,缓存字符读出,以便有效的读出单个字符,数组和字符串

2. 构造方法

//默认缓冲字符大小8192
private static int defaultCharBufferSize = 8192;

//创建一个使用指定大小输入缓冲区的缓冲字符输入流。
public BufferedReader(Reader in, int sz) {
        super(in);
        if (sz <= 0)
            throw new IllegalArgumentException("Buffer size <= 0");
        this.in = in;
        cb = new char[sz];
        nextChar = nChars = 0;
    }
    
public BufferedReader(Reader in) {
        this(in, defaultCharBufferSize);
    }    

3. 涉及变量

    private Reader in;

    private char cb[];
    private int nChars, nextChar;

    private static final int INVALIDATED = -2;
    private static final int UNMARKED = -1;
    private int markedChar = UNMARKED;
    private int readAheadLimit = 0; /* Valid only when markedChar > 0 */

    /** If the next character is a line feed, skip it */
    private boolean skipLF = false;

    /** The skipLF flag when the mark was set */
    private boolean markedSkipLF = false;

    private static int defaultCharBufferSize = 8192;
    private static int defaultExpectedLineLength = 80;

4. 涉及方法

  //读取单字符
public int read() throws IOException {
        synchronized (lock) {
            ensureOpen();
            for (;;) {
                if (nextChar >= nChars) {
                    fill();
                    if (nextChar >= nChars)
                        return -1;
                }
                if (skipLF) {
                    skipLF = false;
                    if (cb[nextChar] == '\n') {
                        nextChar++;
                        continue;
                    }
                }
                return cb[nextChar++];
            }
        }
    }
//读取数组
int read1(char[] cbuf, int off, int len){
    ...
}

//读取一个文本行,默认false
String readLine(boolean ignoreLF) throws IOException {
    ...
}

//跳过几个
long skip(long n)

//判断该流是否确认被读取
boolean ready()

//标记流中当前位置
mark

//重置当前流
void reset()

三、举例

private static void systemIn(File file) throws IOException {
        //接受键盘输入的数据,以缓存字节读取方式从标准IO(键盘)中读取数据,所以要先把标准IO(System.in)转换成字符导向的stream
        Reader reader = new InputStreamReader(System.in);
        BufferedReader bufferedReader = new BufferedReader(reader);
        System.out.println("请输入:");
        String str = bufferedReader.readLine();;
        System.out.println("SystemIn:"+str);
        System.out.println("输入q结束");
        int ff;
        do{
            ff = bufferedReader.read();
            System.out.println((char)ff);
        }while (ff != 'q');

        //从String中读取对象
        StringReader in2 = new StringReader(str);
        int c;
        StringBuilder string = new StringBuilder();
        while ((c = in2.read()) != -1){
            string.append((char) c + "\n");
            System.out.println("String:"+(char)c);
        }

        //读取单个字节
        InputStreamReader inputStreamReader = new FileReader(file);
        BufferedReader bufferedReader1 = new BufferedReader(inputStreamReader);
        char[] chars = new char[5];
        while (bufferedReader1.read(chars,0,chars.length) != -1){
            string.append(String.valueOf(chars)).append("\n");
            System.out.println("chars:"+String.valueOf(chars));
        }

        reader.close();
        bufferedReader.close();

        Writer writer = new OutputStreamWriter(new FileOutputStream(file));
        BufferedWriter bufferedWriter = new BufferedWriter(writer);
        bufferedWriter.write(str);
        bufferedWriter.write(string.toString());
        bufferedWriter.write(str);
        bufferedWriter.close();

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值