JAVA NiO Series (iii) Buffer interpretation

Source: Internet
Author: User

Buffer classification

The buffer in NiO is used to interact with the channel, where the data is read from the channel into the buffer and written to the channel from the buffer. Buffer is like an array that can hold more than one type of data. Each of the basic data types has a corresponding buffer class:

Properties of the buffer

1, capacity (capacity): Buffer is an array, at the initialization of a fixed size, this value is the capacity. Capacity is immutable and once the buffer is full, it needs to be emptied to continue reading and writing.

2, Position (position): Indicates the current position, 0 when initialized, and when data of one base data type is written to buffer, position moves forward to the next buffer cell that can insert data. The position maximum value can be capacity-1.

3. Limit: In buffer write mode, limit indicates how much data you can write to buffer, size equals capacity, and in buffer read mode, limit indicates how much data can be read from the buffer, so when you switch buffer to read mode, Limit is set to the position value in write mode.

one, the use of NiO for file content replication:
 Public classbuffertest{ Public Static voidMain (string[] args)throwsException {fileinputstream fis=NewFileInputStream ("D:/in.txt"); FileChannel Channel=Fis.getchannel (); FileOutputStream Fos=NewFileOutputStream ("D:/out.txt"); FileChannel Channel1=Fos.getchannel (); //Initializing buffersBytebuffer buffer = bytebuffer.allocate (20); System.out.println ("Size of Channel file:" +channel.size ()); System.out.println ("Current position at Buffer initialization:" +buffer.position ()); System.out.println ("Write-writable limit for buffer initialization:" +buffer.limit ()); System.out.println ("---------Cycle begins-----"); //determine if the data in the channel is read complete         while(-1! =channel.read (buffer)) {System.out.println ("Buffer write mode current position:" +buffer.position ()); System.out.println ("Limit in buffer write mode:" +buffer.limit ()); //to switch the buffer from write mode to read modeBuffer.flip (); System.out.println ("Buffer read mode current position:" +buffer.position ()); System.out.println ("Limit in buffer read mode:" +buffer.limit ()); //determine if there is data in the buffer to read             while(Buffer.hasremaining ()) {channel1.write (buffer);        } buffer.clear ();        } channel.close ();        Channel1.close ();    Fis.close (); }}

Execution Result:

The size of the channel file: the current position when the buffer is initialized:0 The writable limit when the buffer is initialized:---------the start of theloop----- The current position in the buffer write mode:  Limit in buffer write mode: buffer read mode current position:0 limit in buffer read mode: Buffer Write mode current position: buffer Write mode limit:20 buffer read mode current position:0 limit in buffer read mode:16

1, the size of the file is 36 bytes, the size of the buffer initialization is 20 bytes, the program took two read operations, the completion of the file content replication.

2, you can see, in the buffer write mode, the size of limit is always equal to capacity, whereas in read mode, limit equals the size of the position before the mode switch.

Ii. Allocation of buffer

The capture of the buffer object needs to be allocated, and each type of buffer object has a allocate method. Let's take the Bytebuffer object in the program as an example:

Bytebuffer buffer = bytebuffer.allocate (20);

We go to follow the source code:

 1  public  static  Bytebuffer Allocate (int   capacity) { Span style= "color: #008080;" >2  if  (Capacity < 0)  3  new   IllegalArgumentException ();  4  return  new   Heapbytebuffer (capacity, capacity);  5 } 
Heapbytebuffer (intint lim) {        //  package-private    SuperNew  byte[cap], 0);

A byte array with a cap size has been created here (new Byte[cap])

Bytebuffer int int int int cap,    //  package-private         byte int offset)    {    super(Mark, POS, Lim, CAP);     this. HB = HB;     this. offset = offset;    }
Buffer (intMarkintPosintLimintCAP) {//package-private    if(Cap < 0)        Throw Newillegalargumentexception ();  This. Capacity =cap;    Limit (LIM);    Position (POS); if(Mark >= 0) {        if(Mark >POS)Throw Newillegalargumentexception ();  This. Mark =Mark; }    }

The creation of arrays has been created within the Bytebuffer class, in the parent class buffer, to initialize some public properties, such as capacity, limits, location, and so on.

Third, the buffer mode switch

Buffer.flip () This method is used to switch the buffer from write mode to read mode, which is a fixed notation, the source code of the method is as follows:

 Public Final Buffer Flip () {    = position;     = 0;     =-1;     return  This ;    }

Calling the flip () method resets position back to 0 and sets the limit to the value of the previous position.

Iv. Methods of Remaind
 Public Final Buffer Rewind () {    = 0;     =-1;     return  This ;    }

Setting the location of the position to 0 means that all data in the buffer can be reread, and the limit remains the same.

Five, Clear method
1   Public Final Buffer Clear () {2     position = 0; 3     Limit = capacity; 4     Mark =-1; 5     return this;

1, once the data in the buffer to read, you need to make buffer ready to be written again, this time you can call the clear method to complete.

2. The Clear method sets position to the value 0,limit is set to capacity, which means that buffer is emptied, but the concept of this emptying is that the write data can start at the specified position in the buffer, but the data in buffer is not deleted.

3, if there is still data in the buffer is not read, this time to call the clear method will cause those data is "forgotten", because there is no tag tells you which is read which is not read.

Vi. writing data to buffer

1, through channel writing;

2. Write by the put method of buffer:

Buffer.put ("Channel". GetBytes ());
Vii. reading data from buffer

1, through the channel reading;

2. Read by the Get method of buffer:

byte b = Buffer.get ();

JAVA NiO Series (iii) Buffer interpretation

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.