aFile.close();
Buffer
Java NIO Buffers and Channels are used in combination,Read from channels into buffer, writtern from buffers into channels
Buffer Usage calls buffer to write data to buffer. the flip () method uses buffer. the get () method calls buffer to obtain data. clear () or buffer. compact () clears read data
RandomAccessFile aFile = new RandomAccessFile(data/nio-data.txt , rw);
FileChannel inChannel = aFile.getChannel();
//Create Buffer with capacity of 48 byte
ByteBuffer buf = ByteBuffer.allocate(48);
-
int bytesRead = inChannel.read(buf);
-
while(bytesRead!=-1){
-
buf.flip(); //make buffer ready for read
-
while(buf.hasRemaining()){
System.out.print((char) buf.get()); // read 1 byte at a time
}
-
buf.clear(); //make buffer ready for writing
bytesRead = inChannel.read(buf);
}
Buffer Capacity, Position and Limit
Capacity
When a Buffer is created, a memory block of the specified size is allocated, and only the fixed size of data can be written to the buffer when writing data. If the Buffer is full, read or clear is required to continue writing.
Position
Position: The reading mode and mode have different meanings. After Bufer init, the Position value is 0. when data is written to one byte, the Position of long etc Buffer is moved to the next Position. AndPosition<=Capacity-1
Whenfilp()When reading data from the Bufferset position = 0, Position will move down with the reading process;
Limit
In Write mode, Limit is equal to the value of Capacity, indicating how much data can be written to the Buffer.
Callfilp()In Reade Modeset limit = positionIndicates the maximum amount of data that can be read.
Commonly used Buffer implementation bytebuffermappedbytebuffercharbufferdoublebufferfloatbufferintbufferlongbuffer=buffersomemethods of BufferAllocating a Buffer
Useallocate()To allocate the Buffer size.
ByteBuffer buf = ByteBuffer. allocate (48 );
CharBuffer buf = CharBuffer. allocate (1024 );
Write Data to a Buffer
There are two ways to write data to the Buffer:
Read data from the Channel and write data into the Buffer. Call the Buffer.put()Method to write data
Int bytesRead = inChannel. read (buf); // read into buffer.
Buf. put (127 );
Flip ()
Convert the write status to the read status. Action:set limit = position ; set position=0 ;
Reading Data from a Buffer
Two methods:
Read data from the Buffer to the Channel to read the data in the Buffer. You can use the built-in buffer method.get()Etc
// Read from buffer into channel.
Int bytesWritten = inChannel. write (buf );
Byte aByte = buf. get ();
Rewind ()
set position=0
Mark () and reset ()
Mark is used until the position of the hitting record. Then, you can use the reset method to reset the position to the position of the mark record.
Scatter/Gather/Transfers
The Channel can read data into multiple buffers.
The Channel can write data from multiple buffers to the Channle.
Channels can be converted between Channle, includingtransferFrom() & transferTo
Scatter Reads:
For example, I read the html header part to the first buffer and read the body part to the second Buffer.
ByteBuffer header = ByteBuffer.allocate(128);
ByteBuffer body = ByteBuffer.allocate(1024);
-
ByteBuffer[] bufferArray = { header, body };
-
channel.read(buffers);
Gather Writes
ByteBuffer header = ByteBuffer.allocate(128);
ByteBuffer body = ByteBuffer.allocate(1024);
-
//write data into buffers
-
ByteBuffer[] bufferArray = { header, body };
-
channel.write(buffers);
TransfersTransferFrom ()
RandomAccessFile fromFile = new RandomAccessFile(fromFile.txt, rw);
FileChannel fromChannel = fromFile.getChannel();
-
RandomAccessFile toFile = new RandomAccessFile(toFile.txt, rw);
FileChannel toChannel = toFile.getChannel();
-
long position = 0;
long count = fromChannel.size();
-
toChannel.transferFrom(fromChannel, position, count);
TransferTo ()
RandomAccessFile fromFile = new RandomAccessFile(fromFile.txt, rw);
FileChannel fromChannel = fromFile.getChannel();
-
RandomAccessFile toFile = new RandomAccessFile(toFile.txt, rw);
FileChannel toChannel = toFile.getChannel();
-
long position = 0;
long count = fromChannel.size();
-
fromChannel.transferTo(position, count, toChannel);
Selector
The Selector component can run to determine multiple channels and dynamically decide which Channel to use to perform Read or Write operations. You can use this component to launch a Thread to manage multiple Channels or multiple network connection Channels.
Create a Selector
UseSelector.open()Method To create a Selector
Selector selector = Selector. open ();
Register Channels to Selector
To allow Selector to manage Channels, you need to callSelector.register()Register with Selector
Channel. configureBlocking (false); // The Channel must be in non-blocking mode to be used with a Selector
SelectionKey key = channel. register (selector, SelectionKey. OP_READ );
When registering a Channel, you must specify the events that the Channel needs to care about. The events include:
Connect-> SelectionKey. OP_CONNECTAccept-> SelectionKey. OP_ACCEPTRead-> SelectionKey. OP_READWrite-> SelectionKey. OP_WRITE
If you register multiple events, you can useint interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;Passint interestSet = selectionKey.interestOps();All Selector's events can be obtained.
Simple Demo:
-
Selector selector = Selector.open();
-
channel.configureBlocking(false);
-
SelectionKey key = channel.register(selector, SelectionKey.OP_READ);
-
-
while(true) {
-
int readyChannels = selector.select();
-
if(readyChannels == 0) continue;
-
-
Set selectedKeys = selector.selectedKeys();
-
Iterator keyIterator = selectedKeys.iterator();
-
while(keyIterator.hasNext()) {
-
SelectionKey key = keyIterator.next();
-
if(key.isAcceptable()) {
// a connection was accepted by a ServerSocketChannel.
-
} else if (key.isConnectable()) {
// a connection was established with a remote server.
-
} else if (key.isReadable()) {
// a channel is ready for reading
-
} else if (key.isWritable()) {
// a channel is ready for writing
}
-
keyIterator.remove();
}
}