I. Overview
Starting with JDK1.4, Java provides a new set of improved input/output processing features, collectively known as NIO (new I/O). A number of new classes have been added to handle input and output, which are placed under the Java.nio package and sub-packages, and are rewritten for many classes in the original java.io package, adding functionality that satisfies nio. NiO uses a memory-mapped file to process input and output, and NIO maps a section of a file or file into memory so that it can access the file as if it were in memory.
NIO has the same effect and purpose as the original I/O, but does it use a different approach? block I/O. The efficiency of block I/O can be much higher than flow I/O.
Flow vs. block comparison
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.
The stream-oriented I/O system processes data one byte at a time. An input stream produces one byte of data, and one output stream consumes one byte of data. Creating filters for streaming data can be very easy. It is relatively straightforward to link several filters so that each filter is only responsible for a single part of the complex processing mechanism. On the downside, flow-oriented I/O is usually quite slow.
A block-oriented I/O system processes data as a block. Each operation generates or consumes a block of data in one step. Processing data by block is much faster than processing data by (streaming) bytes. But block-oriented I/O lacks the elegance and simplicity of some stream-oriented I/O.
There are several core objects in NiO that need to be mastered: buffer, channel, selector (Selector).
Second, 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. specifically, the following picture is understood:
The diagram above depicts the process of sending data from a client to the server and then receiving the data from the server. When the client sends data, the data must be stored in buffer, and then the contents of the buffer are written to the channel. The receiving data on this side of the server must read the data into buffer through the channel and then take the data out of buffer.
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:
Here is an example of a simple use of intbuffer:
PackageCom.demo.nio;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:
Iii. Channel Channels
Channel is similar to stream in traditional IO. Although very similar, but there is a big difference, the main difference is: the channel is bidirectional, through one channel can be read, can also write, and stream can only be one-way operation, through a stream can only read or write, For example, InputStream can only be read operation, OutputStream can only write operations;
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:
A channel represents an open connection to an entity such as a hardware device, file, network socket, or a program component that can perform one or more different I/O operations. All channel is not created by the constructor, but rather the traditional node InputStream, OutputStream Getchannel method to return the response channel.
The three most commonly used methods of the channel are map, read, and write, where the map method maps some or all of the data corresponding to the channel into Bytebuffer, and the read or write method has a series of overloaded forms. These methods are used to read data from buffer or write data to buffer.
1. 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 { Public Static 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 (); } }
2. 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). Write data from channel to buffer
Here is a simple example of using NIO to write data to a file:
PackageCom.demo.nio;ImportJava.io.FileOutputStream;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.FileChannel; Public classProgram {Private Static Final byteMessage[] = {83, 111, 109, 101, 32, 98, 121, 116, 101, 115, 46 }; Public Static 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 (); }}
Four, selector selector
The selector class is the core class of NiO, andselector is able to detect if there are events on multiple registered channels, and if events occur, get the events and then respond to each event accordingly. This way, you can manage multiple channels with just one single thread, that is, managing multiple connections. This allows the function to be called only when the connection actually has a read-write event, which greatly reduces overhead and eliminates the need to create a thread for each connection, to maintain multiple threads, and to avoid the overhead of context switching between threads.
A key class related to selector is Selectionkey, a selectionkey that represents an event that arrives, and these 2 classes form the key logic of the service-side processing business.
Java Nio2:nio Overview