Java IO Learning (11) The cognitive, source and example of buffered input streams

Source: Internet
Author: User
Tags constructor count int size reset valid volatile

Bufferedinputstream (buffered input stream) 's cognition, source code and example

This chapter contains 3 sections: Bufferedinputstream Introduction, Bufferedinputstream source code, and Bufferedinputstream usage examples.

Bufferedinputstream Introduction

Bufferedinputstream is the buffered input stream. It inherits from FilterInputStream.

The role of Bufferedinputstream is to add functionality to another input stream, for example, to provide "buffering" and to support "mark ()" and "Reset () Reset methods."

The Bufferedinputstream is essentially implemented through an internal buffer array. For example, when a new input stream corresponds to a bufferedinputstream, and when we read the input stream's data through read (), Bufferedinputstream fills the input stream's data into the buffer in batches. Each time the data in the buffer is read, the input stream fills the data buffer again, and so on until we have finished reading the input stream data location.

Bufferedinputstream Function List

Bufferedinputstream (InputStream in)
Bufferedinputstream (inputstream in, int size)
     
synchronized int     Available ()
void Close     ()
synchronized void     mark (int readlimit)
boolean     marksupported ()
synchronized int     read ()
synchronized int     read (byte[] buffer, int offset, int byteCount)
synchronized void     Reset ()
synchronized long     Skip (long ByteCount)

Bufferedinputstream Source Analysis (based on jdk1.7.40)

Package java.io;
     
Import Java.util.concurrent.atomic.AtomicReferenceFieldUpdater; public class Bufferedinputstream extends FilterInputStream {//The default buffer size is 8192 bytes//Bufferedinputstream will be based on "buffered Zone Size "to fill the buffer successively;/That is, the bufferedinputstream fills the buffer, the user reads the buffer, and after reading, Bufferedinputstream fills the buffer again.
     
    So loop until you finish reading the data ... private static int defaultbuffersize = 8192;
     
    Buffer array protected volatile byte buf[];
    The atomic update of the cached array. This member variable, together with the volatile keyword of the buf array, constitutes the implementation of the atomic update function of the BUF array, that is, when the Bufferedinputstream object is manipulated in multiple threads, both BUF and Bufupdater are atomic ( The data accessed by different threads is the same) private static final Atomicreferencefieldupdater<bufferedinputstream, byte[]> Bufupdat
     
    ER = Atomicreferencefieldupdater.newupdater (bufferedinputstream.class, Byte[].class, "buf");
    The number of valid bytes in the current buffer.
    Note that this refers to the number of valid bytes in the buffer, not the number of valid bytes in the input stream.
     
    protected int count;
    Index of the position of the current buffer/note, this is the index of the location of the buffer, not the index of the position in the input stream.
     
    protected int pos; Mark position of current buffer//Markpos and RESET () is meaningful with use.
    Procedure://(01) through the mark () function, the value of the POS is saved to the Markpos. (02) through the Reset () function, the value of POS will be reset to Markpos.
    Then read () reads the data, starting at the location where Mark () is saved.
     
    protected int markpos =-1;
	Marklimit is the maximum value for the tag. See this column more highlights: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java///about the principle of marklimit, we at the back of the Fill () The function analysis is described in detail.
    This is very important for understanding bufferedinputstream.
     
    protected int marklimit;
        Gets the input stream private InputStream Getinifopen () throws IOException {InputStream input = in;
        if (input = = null) throw new IOException ("Stream closed");
    return input;
        }//Get buffered Private byte[] Getbufifopen () throws IOException {byte[] buffer = BUF;
        if (buffer = null) throw new IOException ("Stream closed");
    return buffer; }//constructor: Create a new Bufferedinputstream public bufferedinputstream with a buffer size of 8192 (InputStream in) {This (in, D
    Efaultbuffersize); }//constructor: New BUFFEREDINPU with specified buffer sizeTstream Public Bufferedinputstream (inputstream in, int size) {super (in);
        if (size <= 0) {throw new IllegalArgumentException ("Buffer size <= 0");
    } BUF = new byte[size];
    //Read the data from the input stream and populate it in the buffer.
    The function will be described in detail later!
        private void Fill () throws IOException {byte[] buffer = Getbufifopen ();            if (Markpos < 0) pos = 0; /* No mark:throw away the buffer */else if (POS >= buffer.length)/No room left in buffer * * * *
                F (Markpos > 0) {/* can throw away early part of the buffer */int sz = Pos-markpos;
                System.arraycopy (buffer, markpos, buffer, 0, SZ);
                pos = SZ;
            Markpos = 0;   else if (buffer.length >= marklimit) {markpos =-1;        /* Buffer got too big, invalidate mark */pos = 0;       /* Drop Buffer contents * *} else {     /* Grow buffer */INT NSZ = pos * 2;
                if (Nsz > Marklimit) nsz = Marklimit;
                byte nbuf[] = new Byte[nsz];
                System.arraycopy (buffer, 0, nbuf, 0, POS);
                if (!bufupdater.compareandset (this, buffer, nbuf)) {throw new IOException ("Stream closed");
            buffer = Nbuf;
        Count = pos;
        int n = getinifopen (). Read (buffer, POS, buffer.length-pos);
    if (n > 0) Count = n + pos; //Read Next byte public synchronized int read () throws IOException {//If the data in the buffer has been read, call fill () to read the next part from the input stream
            Data to populate the buffer if (POS >= count) {fill ();
        if (POS >= count) return-1;
    ///reads the specified byte from the buffer return Getbufifopen () [pos++] & 0xFF; //Writes the data in the buffer to byte array B. Off is the starting position of byte array B, Len is write length private int read1 (byte[] b, int oFF, int len) throws IOException {int avail = Count-pos;
            if (avail <= 0) {//acceleration mechanism. If the length of the read is greater than the length of the buffer and there is no markpos,//It is read directly from the original input stream to avoid unnecessary copy (stream from raw input to buffer, read buffer full data, empty buffer,//Refill into the original input stream data) if (Len >= getbufifopen (). Length && Markpos < 0) {return Getinifopen (
            ). Read (b, off, Len);
            //If the data in the buffer has been read, call Fill () to fill the buffer fill () by reading the next part of the data from the input stream;
            avail = Count-pos;
        if (avail <= 0) return-1; int cnt = (Avail < len)?
        Avail:len;
        System.arraycopy (Getbufifopen (), POS, B, off, CNT);
        POS + cnt;
    return CNT; //Writes the data in the buffer to byte array B.
        Off is the starting position of byte array B, Len is write length public synchronized int read (byte b[], int off, int len) throws IOException { Getbufifopen (); Check for closed stream if (off | len | (off + len) | (B.length-(off + len))
< 0) {            throw new Indexoutofboundsexception ();
        else if (len = = 0) {return 0;
        ///Read to the specified length of data before returning int n = 0; for (;;)
            {int nread = Read1 (b, off + N, len-n); if (nread <= 0) return (n = = 0)?
            Nread:n;
            n + = Nread;
            if (n >= len) return n;
            If not closed but no bytes available, return inputstream input = in;
        if (input!= null && input.available () <= 0) return n; }//Ignore n bytes public synchronized long Skip (long N) throws IOException {Getbufifopen ();//CHEC
        K for closed stream if (n <= 0) {return 0;
     
        Long avail = Count-pos;
                if (avail <= 0) {//If no mark position set then don ' t keep in buffer If (Markpos <0)
  Return Getinifopen (). Skip (n);   
            Fill in buffer to save bytes for reset fill ();
            avail = Count-pos;
        if (avail <= 0) return 0; Long skipped = (Avail < n)?
        Avail:n;
        POS + skipped;
    return skipped;
        Whether the next byte is stored readable public synchronized int available () throws IOException {int n = count-pos;
        int avail = Getinifopen (). available (); return n > (integer.max_value-avail)?
    Integer.max_value:n + avail;
    //mark the current position in the buffer.
    Readlimit is Marklimit, about the role of Marklimit, refer to the following instructions.
        Public synchronized void mark (int readlimit) {marklimit = Readlimit;
    Markpos = pos; ///Reset the current position in buffer to the position marked by Mark () public synchronized void Reset () throws IOException {Getbufifopen () ; Cause exception if closed if (Markpos < 0) throw new IOException ("resetting to InvaLid mark ");
    pos = Markpos;
    public boolean marksupported () {return true;
        //Turn off input stream public void close () throws IOException {byte[] buffer; while (buffer = BUF)!= null) {if (bufupdater.compareandset, buffer, null) {INPUTSTR
                EAM input = in;
                in = null;
                if (input!= null) input.close ();
            Return }/Else retry in case a new buf is cased in Fill ()}}}

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.