Java NIO (i) channel and buffer

Source: Internet
Author: User
Tags compact rewind

Java NIO is the new I O, the biggest difference between him and the traditional IO is that it is non-blocking IO.

The main differences between Java NiO and IO:


IO NIO

Stream-oriented buffering

Blocking IO non-blocking IO

No selector

They each apply to different environments, here is only a simple explanation of their differences, specifically see the blog:

http://ifeve.com/java-nio-vs-io/

The core APIs of NIO are Channel, buffer and selector, and this article focuses on the first two.

A simple example

Let's start with a simple example that uses the NIO API to write data to a file and then read it out and print it, which is detailed and can be savored, in addition to an overview of NiO:

http://ifeve.com/channels/

/** * NIO Simple test example, write data to a file and read it out. This example * mainly illustrates the difference between NIO and traditional IO, which requires attention to the use of channel and buffer. * Understanding NIO is buffer-oriented. And Io is flow-oriented. * * The following example to understand the use of NIO, 1 define a channel, 2, define a buffer * 3 Write data to buffer (two meanings of writing, channel related) 4 to read mode 5. Reading buffer data (meaning of Read and Chann El's direction) * */public class Main {public static void main (string[] args) throws IOException {File A = new File ("test.txt"); F (!a.exists ()) {a.createnewfile ();} FileOutputStream out = new FileOutputStream (a);//construct output channel, here use Filechannelfilechannel Outchannel = Out.getchannel () ; String teststr = "Lina, I Love You";//constructs an output cache. Bytebuffer byteBuffer1 = bytebuffer.allocate,//put method writes data to the cache, note that it is write Bytebuffer1.put (Teststr.getbytes ());// The following three lines of code will write data to the file, the Filp () method converts the buffer to read mode, and then writes the data to the file using the channel's Write method. Note that the data written to the file is "read" from Charbuffer, written or read for buffer, not according to the channel, which needs to be understood Bytebuffer1.flip (); while (Outchannel Bytebuffer1.hasremaining ()) {outchannel.write (byteBuffer1);} Outchannel.close (); Out.close (); FileInputStream in = new FileInputStream (a);//construct input channel and buffEr, in contrast to the above, the channel direction is determined by the underlying packaging layer. FileChannel Inchannel = In.getchannel (); Bytebuffer inbuffer = bytebuffer.allocate (512);//loop read the file data, write to buffer, note that this is still written to Bufferwhile (Inchannel.read (Inbuffer) !=-1) {}//converted to read mode, after the Flip method call, there are some changes in buffer that are not discussed here. Inbuffer.flip (); byte[] Dest = new Byte[inbuffer.limit ()];//reads data into a byte array. Inbuffer.get (dest, 0, Inbuffer.limit ()); Inchannel.close (); In.close (); System.out.println (New String (dest));}


Channel

Official document definition channel means "connection to an entity", which can be a device, file, socket, etc. The interface definition of the channel is simple, and the JDK provides several implementations.

Public interface Channel extends Closeable {public      boolean isOpen ();      public void Close () throws IOException; }


Showing the channel system, Writablebytechannel and Readablebytechannel respectively expanded the channel interface, adding read and write functions, of which the most common implementation has been in red box up, They are suitable for different occasions respectively.

FileChannel read and write data from a file, corresponding to Fileinput/outputstream

Datagramchannel can read and write data on the network through UDP. Correspondence Datagramsocket

Socketchannel can read and write data in the network via TCP. Socket in the corresponding IO

Serversocketchannel can listen for incoming TCP connections, like a Web server. A socketchannel is created for each new incoming connection. ServerSocket in the corresponding IO

Buffer

First, a graph is posted to indicate the relationship between channel and buffer, that is, the channel reads and writes data through buffer. About buffer,http://ifeve.com/buffers/, the above address translation is very good, here to pick out part of the content.


Basic usage

In a simple example, the basic usage of channel and buffer has been explained here, to make a simple summary,

Reading and writing data using buffer typically follows these four steps:

1. Write data to Buffer

2. Call the Flip () method

3. Reading data from buffer

4. Call the Clear () method or the compact () method

When data is written to buffer, buffer records how much data is written. Once you are reading the data, you need to switch the buffer from write mode to read mode via the Flip () method. In read mode, all data written to buffer can be read.

Once all the data has been read, the buffer needs to be emptied so that it can be written again. There are two ways to clear a buffer: Call the Clear () or compact () method. The clear () method empties the entire buffer. The compact () method clears only the data that has been read. Any unread data is moved to the beginning of the buffer, and the newly written data is placed behind the buffer's unread data.

The properties of the buffer

Buffer has three basic properties capacity limit position.

Capacity refers to the size of the buffer, which is determined when buffer is established.

Limit when buffer is in write mode, it refers to how much data can be written, in read mode, and how much data can be read.

Position when buffer is in write mode, it refers to the location of the next write data, in read mode, where the data is currently being read. Read and write one data per position+1

That is, limit and position do not have the same meaning when reading/writing in buffer. When you call the flip method of buffer and the write mode changes to read mode,

Limit (read) =position (write)

Position (read) = 0;

Type of buffer

There are several types of buffer, and different buffer provides different ways to manipulate the data in buffer.


Operation of Buffer Write data

There are two cases of writing data to buffer:

1. Write from channel to buffer, as in example the channel reads data from a file and writes to the channel

2. Call the Put method directly and write the data inside

Flip ()

This operation has been explained, converting buffer to read mode

Read data

There are two ways of reading data from buffer:

1. Read data from buffer to channel.

2. Use the Get () method to read data from buffer.

Rewind ()

Buffer.rewind () sets the position back to 0, so you can reread all the data in the buffer. The limit remains unchanged and still indicates how many elements (Byte, char, and so on) can be read from the buffer.

Clear () and compact () methods

Once you have finished reading the data in buffer, you need to make buffer ready to be written again. Can be done through the clear () or compact () method.

If the call is the clear () method, position will be set back to the value 0,limit to capacity. In other words, Buffer is emptied. The data in buffer is not cleared, but these tags tell us where we can start writing data to buffer.

If there are some unread data in buffer and the clear () method is called, the data will be "forgotten", meaning no more tags will tell you what data has been read or not.

If you still have unread data in buffer and you need that data later, but you want to write some data first, use the compact () method.

The Compact () method copies all unread data to the beginning of the buffer. The position is then set to the last unread element just behind it. The Limit property is still set to capacity, just like the clear () method. Now buffer is ready to write the data, but it will not overwrite the unread data.

Java NIO (i) channel and buffer

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.