Java NIO usage and Principle Analysis (1) from the online data collation

Source: Internet
Author: User

There are several core objects in NiO that need to be mastered: buffer, channel, selector (Selector).

Buffer buffers

Buffer is actually a container object, more directly, is actually an array, in the NIO library, all the data are processed in buffer. When the data is read, it is read directly into the buffer, and it is written to the buffer when the data is written, and any time the data in the NIO is accessed, it is placed in the buffer. In a stream-oriented I/O system, all data is written directly or read directly to the stream object.

In NiO, all of the buffer types are inherited from the abstract class buffer, the most common is bytebuffer, for the basic type of Java, basically have a specific buffer type corresponding to it, the inheritance between them as shown:

The following is a simple example of using Intbuffer:

    ImportJava.nio.IntBuffer;  Public classTestintbuffer { Public Static voidMain (string[] args) {//allocates a new int buffer with parameters of buffer capacity//the current position of the new buffer will be zero, and its bounds (the restricted position) will be its capacity.  It will have a lower-level implementation array with an array offset of zero. Intbuffer buffer = intbuffer.allocate (8);  for(inti = 0; I < buffer.capacity (); ++i) {intj = 2 * (i + 1); //writes the given integer to the current position of this buffer, incrementing the current positionBuffer.put (j); }                    //resets this buffer, sets the limit to the current position, and then sets the current position to 0Buffer.flip (); //see if there are elements between the current position and the restricted position             while(Buffer.hasremaining ()) {//reads an integer from the current position of this buffer, and increments the current position                intj =Buffer.get (); System.out.print (J+ "  "); }                }            }  

After running, you can see:

We will continue to analyze the buffer object and several of its important properties later.

Channel channels

A channel is an object through which data can be read and written, and of course all data is handled through the buffer object. We never write bytes directly into the channel, but instead write the data to a buffer that contains one or more bytes. The same does not read the bytes directly from the channel, but instead reads the data from the channel into the buffer and fetches the byte from the buffer.

In NiO, a variety of channel objects are provided, and all channel objects implement the channels interface. The inheritance relationship between them is as follows:

Using NIO to read data

As we said earlier, any time the data is read, it is not read directly from the channel, but is read from the channel to the buffer. So the use of NIO to read data can be divided into the following three steps:
1. Get Channel from FileInputStream
2. Create buffer
3. Reading data from the channel into buffer

Here is a simple example of using NIO to read data from a file:

ImportJava.io.*; ImportJava.nio.*; Importjava.nio.channels.*;  Public classProgram {Static  Public voidMain (String args[])throwsException {fileinputstream fin=NewFileInputStream ("C:\\Test.txt"); //Get channelFileChannel FC =Fin.getchannel (); //Creating BuffersBytebuffer buffer = bytebuffer.allocate (1024); //read data to bufferfc.read (buffer);                    Buffer.flip ();  while(Buffer.remaining () >0) {              byteb =Buffer.get (); System.out.print ( (Char) (b));      } fin.close (); }  }

Write Data using NiO

Using NIO to write data is similar to the process of reading data, and the same data is written to a buffer instead of directly to the channel, and can be divided into three steps:
1. Get Channel from FileInputStream
2. Create buffer
3. Writing data from the channel to buffer

Here is a simple example of using NIO to write data to a file:

[Java] View plain copyprint?ImportJava.io.*; ImportJava.nio.*; Importjava.nio.channels.*;  Public classProgram {Static Private Final byteMessage[] = {83, 111, 109, 101, 32,              98, 121, 116, 101, 115, 46 }; Static  Public voidMain (String args[])throwsException {fileoutputstream fout=NewFileOutputStream ("C:\\Test.txt" ); FileChannel FC=Fout.getchannel (); Bytebuffer Buffer= Bytebuffer.allocate (1024 );  for(inti=0; i<message.length; ++i) {buffer.put (message[i]);                            } buffer.flip ();                            Fc.write (buffer);          Fout.close (); }      } 

Java NIO usage and Principle Analysis (1) from the online data collation

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.