The use and principle of BufferedReader and bufferedwriter of Java-io flow

Source: Internet
Author: User

The purpose of BufferedReader and BufferedWriter is to enhance the reading and writing operations of FileReader and FileWriter, and how to enhance it, similar to the use of StringBuilder, is to put the data into one of their char arrays before manipulating the char array.

Using the buffer character stream is a decorative mode to the FileReader and other functions of the enhancement, decorator mode and inheritance can achieve functional enhancements, but the decorator can do more flexible, do not make the inheritance tree too complex.

Here is a small part of the BufferedWriter source code

public class BufferedReader extends reader {    private reader in;  The constructor needs to use the reader    private char cb[];   Its own char array, which itself the read () method will be to access this array, this array is the buffer    private int nchars, Nextchar;     The index of the position and number of the char array

Next look at the BufferedWriter source of the Read () method:

    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++];}}    

This read () method is a char array that accesses the BufferedReader itself, and calls the fill () method to repopulate the char array when it finds that the elements of the array have been accessed. This is the essence of the character stream that uses the buffer.

Similarly, BufferedWriter also writes the data to its own char array, which is then written to the file when it is refreshed.

Attention:

1, when the use of BufferedWriter or BufferedReader, is the filereader of the assignment to the BufferedReader inside the reader object, Therefore, to save the data to the file when calling the parameters of the input BufferedReader reader is invalid, you need to use BufferedReader to refresh or close BufferedReader after the data will be saved to the file;

2. When the BufferedReader is closed, the reader passed in as a parameter will be closed.

3, BufferedReader has a special method Readerline (), the function is to read a line, the principle is read from the char array, determine whether to encounter a newline character, is the word to return.

Here's a bufferedreader code that you write yourself based on the IO video of the Preach Intelligence podcast:

public class Mybufferedreader {private Reader reader;    private int count;    private int position;    Private char[] Contentarray = new char[1024];    private int ch;    Private final String line_separate = System.getproperty ("Line.separate");    Public Mybufferedreader (Reader reader) {this.reader = reader;            } public int myreader () throws IOException {if (count = = 0) {count = Reader.read (Contentarray);        Position = 0;        } if (count = =-1) {return-1;        } count--;        ch = contentarray[position];        position++;    return ch;        } public String Myreadline () throws IOException {StringBuilder sb = new StringBuilder (256);        int ch = 0;            while (ch = myreader ())! =-1) {if (ch = = ' \ r ') {continue;            } if ((char) ch = = ' \ n ') {return sb.tostring ();        } sb.append ((char) ch); } if (sb.Length () > 0) return sb.tostring ();    return null;    } public void Close () throws IOException {reader.close (); }}

Here is the code for the call:

        Try (FileWriter FileWriter = new FileWriter ("Buffer.txt")) {            try (bufferedwriter bufferedwriter = new BufferedWriter ( FileWriter)) {                int count = 3;                while (count! = 0) {                    bufferedwriter.write ("123456");                    Bufferedwriter.newline ();                    Bufferedwriter.write ("abcdef");                    Bufferedwriter.newline ();                    count--        ;        }}} Try (filereader FileReader = new FileReader ("Buffer.txt")) {            Mybufferedreader BufferedReader = new Mybufferedreader (FileReader);            String line = null;            while (line = Bufferedreader.myreadline ())! = null) {                System.out.println (line);            }        }

The result of the operation is:

Disconnected from the target VM, address: ' 127.0.0.1:26416 ', Transport: ' Socket ' 123456abcdef123456abcdef123456abcdefprocess finished with exit code 0

  

The use and principle of BufferedReader and bufferedwriter of Java-io flow

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.