Java IO Learning (22) BufferedReader (character buffering input stream)

Source: Internet
Author: User
Tags eol int size readline reset stringbuffer

BufferedReader Introduction

BufferedReader is the buffered character input stream. It inherits from reader.

The role of BufferedReader is to add some buffering functionality to other character input streams.

BufferedReader Function List

BufferedReader (Reader in)
BufferedReader (reader in, int size)
     
void close     ()
void     mark (int Marklimit)
boolean  marksupported ()
int      read ()
int      read (char[] buffer, int offset, int Length)
String   readLine ()
boolean  Ready () "
void Reset" (     )
long     Skip (long CharCount)

BufferedReader Source Analysis (based on jdk1.7.40)

Package java.io;
     
    public class BufferedReader extends reader {private reader in;
    Character Buffer private Char cb[];
     
    Nchars is the total number of characters in the CB buffer//Nextchar is the next character to read in the CB buffer position private int nchars, Nextchar; Indicates "Invalid Tag".
    It differs from unmarked in that the unmarked is not set at all.
    (02) and invalidated is set the tag, but the marked position is too long, causing the tag is invalid!
    private static final int invalidated =-2;
    Indicates that the "tag" private static final int unmarked =-1 is not set;
    "Mark" private int markedchar = unmarked; "Mark" can mark the maximum length of a position private int readaheadlimit = 0; /* Valid only when Markedchar > 0///SKIPLF (that is, skip line Feed) is "ignore newline character" Mark private Boolean SKIPLF = Fals
     
    E
     
    When setting tag, the value of the saved SKIPLF is private Boolean MARKEDSKIPLF = false;
    Default character buffer size private static int defaultcharbuffersize = 8192;
     
    Default number of characters per line private static int defaultexpectedlinelength = 80; Create a "Reader" corresponding to the BufferedReader object, SZ is the BufferedReader buffer size 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; //create "reader" corresponding BufferedReader object, the default BufferedReader buffer size is 8k public bufferedreader (reader in) {This
    (in, defaultcharbuffersize);
            }//Ensure "BufferedReader" is open private void Ensureopen () throws IOException {if (in = = null)
    throw new IOException ("Stream closed"); }//Fill buffer function.
    The following two conditions are invoked://(01) The buffer has no data, and fill () can populate the buffer with the data.
    (02) When the buffer data is read, the data of the buffer can be updated by fill () when updates are required.
        private void Fill () throws IOException {//DST indicates "starting position of data filled in CB".
        int DST;
            if (Markedchar <= unmarked) {//without marking, set dst=0.
        DST = 0; else {//Delta represents the "length of the current Tag", which equals "the next read character position" minus the "marked position" difference; int delta = Nextchar-markedchar;
            if (Delta >= readaheadlimit) {//If the length of the current tag exceeds the mark Upper limit (readaheadlimit),//
                Discard the tags!
                Markedchar = invalidated;
                Readaheadlimit = 0;
            DST = 0; else {if (readaheadlimit <= cb.length) {//If the length of the current tag does not exceed the tag cap (readaheadlimit) ",//and the Mark Upper bound (readaheadlimit) is less than/equal to the" buffer length ";//the" next location to be read, distance from the token we marked "is saved to
                    CB in.
                    System.arraycopy (CB, Markedchar, CB, 0, Delta);
                    Markedchar = 0;
                DST = Delta; else {//If the length of the current tag does not exceed the mark Upper limit (readaheadlimit),/and the Mark Upper bound (readaheadlimit) is greater than the slow The length of the dash ";//See more Highlights in this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java///Reset buffer Large
                    Small, and the "next to be read the location, distance from the mark of the distance between the characters" to save to the CB.
          Char ncb[] = new Char[readaheadlimit];          System.arraycopy (CB, Markedchar, NCB, 0, Delta);
                    cb = NCB;
                    Markedchar = 0;
                DST = Delta;
            }//Update Nextchar and nchars Nextchar = nchars = Delta;
        } int n; Do {//reads the data from "in" and stores it in the character array CB;//from the DST location of CB, the number of characters read is CB.LENGTH-DST//n is the actual character read
            If the n==0 (that is, not a read), then continue to read!
        n = in.read (CB, DST, CB.LENGTH-DST);
     
        while (n = = 0);
        If data is read from "in", set Nchars (number of characters in CB) =dst+n,//and Nextchar (position of next read character) =dst.
            if (n > 0) {nchars = DST + N;
        Nextchar = DST; Read a character from BufferedReader that returns the public int read () throws IOException {synchronized () as int
            Lock) {Ensureopen (); for (;;) {//If "buffer data has been read",//The buffer data is updated with fill () First if (Nextchar >= nchars) {fill ();
                if (Nextchar >= nchars) return-1;
                //To "Ignore line breaks",//to treat the next character as a line feed.
                    if (SKIPLF) {SKIPLF = false;
                        if (cb[nextchar] = = ' \ n ') {nextchar++;
                    Continue
            }//Returns the next character return cb[nextchar++]; The data in the buffer is written to the array cbuf. Off is the write start position in the array cbuf, Len is the write length private int read1 (char[] cbuf, int off, int len) throws IOException {//If "buffer data has been
        After being read, the buffer data is updated. if (Nextchar >= nchars) {if (Len >= cb.length && markedchar <= unmarked &&!SKIPLF)
            {return In.read (cbuf, off, Len);
        Fill ();
        If there is no change after the data is updated, exit. if (Nextchar >= nchars) return-1;
            To "Ignore line breaks", do the appropriate processing if (SKIPLF) {SKIPLF = false;
                if (cb[nextchar] = = ' \ n ') {nextchar++;
                if (Nextchar >= nchars) fill ();
            if (Nextchar >= nchars) return-1;
        }///copy character operation int n = math.min (len, Nchars-nextchar);
        System.arraycopy (CB, Nextchar, Cbuf, off, N);
        Nextchar + = n;
    return n;
        The encapsulation of READ1 () has added functions such as "synchronous" and "blocking reads", such as public int read (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 0;
          int n = read1 (cbuf, off, Len);  if (n <= 0) return n;
                while ((n < len) && In.ready ()) {int N1 = Read1 (cbuf, off + N, len-n);
                if (N1 <= 0) break;
            n + = n1;
        } return N; Read one row of data//.
        Ignorelf is "Ignore line break" String ReadLine (Boolean ignorelf) throws IOException {StringBuffer s = null;
     
        int Startchar;
            Synchronized (lock) {ensureopen (); Boolean OMITLF = Ignorelf | |
     
            SKIPLF; Bufferloop:for (;;)
                {if (Nextchar >= nchars) fill ();
                        if (Nextchar >= nchars) {/* EOF */if (s!= null && s.length () > 0)
                    return s.tostring ();
                else return null;
                Boolean EOL = false;
                char c = 0;
     
             int i;   /* Skip a leftover ' \ n ', if necessary/if (OMITLF && (cb[nextchar) = ' \ n ')
                nextchar++;
                SKIPLF = false;
     
            OMITLF = false;
                    Charloop:for (i = Nextchar i < nchars; i++) {c = cb[i]; if (c = = ' \ n ') | | (c = = ' \ r ')]
                        {EOL = true;
                    Break Charloop;
                } Startchar = Nextchar;
     
                Nextchar = i;
                    if (EOL) {String str;
                    if (s = = null) {str = new String (CB, Startchar, I-startchar);
                        else {s.append (CB, Startchar, I-startchar);
                    str = s.tostring ();
                    } nextchar++; if (c = = ' \ r ') {SKIPLF = TruE
                return str;
                } if (s = = null) s = new StringBuffer (defaultexpectedlinelength);
            S.append (CB, Startchar, I-startchar); Read one row of data//.
    The newline character public String ReadLine () throws IOException {return ReadLine (false) is not ignored; }//Skip N-Character public long skip (long N) throws IOException {if (n < 0L) {throw new Ill
        Egalargumentexception ("Skip value is negative");
            } synchronized (lock) {ensureopen ();
            Long r = N;
                while (R > 0) {if (Nextchar >= nchars) fill ();
                if (Nextchar >= nchars)/* EOF/break;
                    if (SKIPLF) {SKIPLF = false;
                    if (cb[nextchar] = = ' \ n ') {nextchar++;
     }           Long d = Nchars-nextchar;
                    if (R <= D) {Nextchar + = r;
                    R = 0;
                Break
                    else {R-= D;
                Nextchar = Nchars;
        } return n-r;
            "Next character" is readable public boolean ready () throws IOException {synchronized (lock) {
     
            Ensureopen ();  If the newline character is omitted to be true, or if the next symbol is a newline character, if so, the if (SKIPLF) {if (Nextchar >= nchars) is ignored
                && In.ready ()) {fill (); } if (Nextchar < nchars) {if (Cb[nextchar] = = ' \ n ') nextch
                    ar++;
                SKIPLF = false; } return (Nextchar < nchars) | |
        In.ready (); }//Always returns TRUE. Because BuffereDreader supports mark (), Reset () public boolean marksupported () {return true; }//marks the next read position for the current BufferedReader.
    On the role of Readaheadlimit, refer to the following instructions. public void mark (int readaheadlimit) throws IOException {if (Readaheadlimit < 0) {throw new Illeg
        Alargumentexception ("Read-ahead limit < 0");
            } synchronized (lock) {ensureopen ();
            Set Readaheadlimit this.readaheadlimit = Readaheadlimit;
            Save the next location to read Markedchar = Nextchar;
        Save the "Do not ignore line breaks" tag MARKEDSKIPLF = SKIPLF;
    }//Resets the next read location of the BufferedReader,//restores it to the location that is saved in Mark ().
            public void Reset () throws IOException {synchronized (lock) {ensureopen ();
                                      if (Markedchar < 0) throw new IOException ((Markedchar = = invalidated) ? "Mark Invalid": "Stream not M"Arked ");
            Nextchar = Markedchar;
        SKIPLF = MARKEDSKIPLF;
                } public void Close () throws IOException {synchronized (lock) {if (in = = null)
            Return
            In.close ();
            in = null;
        CB = NULL; }
    }
}

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.