Introduction to Java NIO components

Buffer

From chapter 1, we learned that a Channel and a Buffer can read and write to each other, which is essentially a piece of memory from which data can be written and then read. To understand how this works, you need to know three properties:

  • Capacity: indicates the size of the Buffer
  • Position: In write mode, position represents the current position. After a data is written, position moves to the next Buffer cell. When Buffer switches from write mode to read mode, position is reset to 0. When data is read from position in the Buffer, position moves forward to the next readable position
  • Limit: In write mode, the Buffer limit indicates the maximum amount of data you can write into the Buffer, so it equals the capacity of the Buffer. When switching to read mode, limit indicates how much data you can read at most

Illustration:

1 Buffer type

  • ByteBuffer
  • MappedByteBuffer
  • CharBuffer
  • DoubleBuffer
  • FloatBuffer
  • IntBuffer
  • LongBuffer
  • ShortBuffer

2 Allocate a Buffer

ByteBuffer buf = ByteBuffer.allocate(48);
Copy the code

3 Write data to the Buffer

int bytesRead = inChannel.read(buf); 
Copy the code

Use the put() method

buf.put(127);
Copy the code

4 Flip operation: flip()

Flip () switches the read and write modes of the Buffer

5 Read data from Buffer

int bytesWritten = inChannel.write(buf);
Copy the code

Use the get() method

byte aByte = buf.get();
Copy the code

6 Clear () and Compact () methods

Prerequisite: Once the Buffer has been read, it needs to be ready to be written again. This can be done using either the clear() or compact() methods. Clear () sets position to 0 and limit to Capacity. Compact () is used to copy all unread data to the start of the Buffer. Position is then set directly after the last unread element. The limit property is set to Capacity as in the clear() method.