New features of the Java NiO and small demo to learn more about NIO

Source: Internet
Author: User
Tags compact

1. Why Use NiO

NIO was created to enable Java programmers to implement high-speed I/O without having to write custom native code. NIO transfers the most time-consuming I/O operations (that is, the fill and fetch buffers) back to the operating system, which can greatly improve speed. The most important difference between the original I/O library (in java.io.*) and NIO is the way data is packaged and transmitted. As mentioned earlier, the original I/O processes the data in a streaming way, and NIO processes the data in chunks.

2.NIO Core object: Buffer

What is a buffer? Buffer is an object that contains some data that you want to write or just read. Adding a Buffer object to the NIO reflects an important difference between the new library and the original I/O. In stream-oriented I/O, you write data directly or read the data directly into the stream object. In the NIO library, all data is processed in a buffer. When the data is read, it is read directly into the buffer. When the data is written, it is written to the buffer. Whenever you access data in NIO, you put it in a buffer.

The most commonly used buffer type is bytebuffer. A bytebuffer can perform get/set operations on its underlying byte array (that is, the acquisition and setting of bytes).

3.NIO Core object: Channel

What is a channel? A channel is an object through which data can be read and written. Compare the NIO with the original I/O and the channel is like a stream. As mentioned earlier, all data is handled through the Buffer object. You never write bytes directly into the channel, instead, you write the data to a buffer that contains one or more bytes. Again, instead of reading the bytes directly from the channel, you read the data from the channel into the buffer and get the byte from the buffer.

Channel type: The difference between a channel and a stream is that the channel is bidirectional. The stream is only moved in one Direction (a stream must be a subclass of InputStream or OutputStream), and the channel can be used for reading, writing, or both.

Instance:

NIO Read File
@Test Public voidRead ()throwsException {//The first step is to get the channel, we get the channel from the FileinpustreamFileInputStream fin =NewFileInputStream ("C:\\users\\administrator\\desktop\\test.txt"); FileChannel Channel=Fin.getchannel (); //the next step is to create a bufferBytebuffer buf = bytebuffer.allocate (1024); StringBuilder SB=NewStringBuilder (); //reads the contents of a file through a channel into a buffer, unread to the end of the file         while((Channel.read (BUF))! =-1) {            //after the flip is called, the pointer is read to the cache header, and the setting can only read the length of the previously written data (not the size of the entire cache capacity)Buf.flip (); //loop to determine if the buffer still has data available             while(Buf.hasremaining ()) {CharB = (Char) Buf.get ();                Sb.append (b); //Read buffer contents, convert to char type} System.out.println (String.valueof (SB)); //Compact (): Only erase data that has been read any unread data is moved to the buffer in fact//The newly written data is placed after the buffer unread databuf.compact (); }    }
NiO Writing Files
@Test Public voidWrite ()throwsIOException {String mess[]= {"09", "099", "665", "655", "355"}; //create file byte output streamFileOutputStream Fout =NewFileOutputStream ("C:\\users\\administrator\\desktop\\test2.txt"); //get the channel from the byte streamFileChannel channel =Fout.getchannel (); //Create buffer Object (allocate assignment)Bytebuffer buffer = bytebuffer.allocate (1024); //write data through a pipeline to a buffer         for(inti = 0; I <mess.length; i++) {buffer.put (Mess[i].getbytes ()); }        //changing the buffer pointerBuffer.flip (); //writes the buffer contents to the channelchannel.write (buffer); //Compactbuffer.compact (); //off-StreamFout.close (); }

New features of the Java NiO and small demo to learn more about NIO

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.