English 中文(简体)
Java NIO - Buffer
  • 时间:2024-12-22

Java NIO - Buffer


Previous Page Next Page  

Buffers in Java NIO can be treated as a simple object which act as a fixed sized container of data chunks that can be used to write data to channel or read data from channel so that buffers act as endpoints to the channels.

It provide set of methods that make more convenient to deal with memory block in order to read and write data to and from channels.

Buffers makes NIO package more efficient and faster as compared to classic IO as in case of IO data is deal in the form of streams which do not support asynchronous and concurrent flow of data.Also IO does not allow data execution in chunk or group of bytes.

Primary parameters that defines Java NIO buffer could be defined as −

    Capacity − Maximum Amount of data/byte that can be stored in the Buffer.Capacity of a buffer can not be altered.Once the buffer is full it should be cleared before writing to it.

    Limit − Limit has meaning as per the mode of Buffer i.e. in write mode of Buffer Limit is equal to the capacity which means that maximum data that could be write in buffer.While in read mode of buffer Limit means the pmit of how much data can be read from the Buffer.

    Position − Points to the current location of cursor in buffer.Initially setted as 0 at the time of creation of buffer or in other words it is the index of the next element to be read or written which get updated automatically by get() and put() methods.

    Mark − Mark a bookmark of the position in a buffer.When mark() method is called the current position is recorded and when reset() is called the marked position is restored.

Buffer Type

Java NIO buffers can be classified in following variants on the basis of data types the buffer deals with −

    ByteBuffer

    MappedByteBuffer

    CharBuffer

    DoubleBuffer

    FloatBuffer

    IntBuffer

    LongBuffer

    ShortBuffer

Important methods of Buffer

As mentioned already that Buffer act as memory object which provide set of methods that make more convenient to deal with memory block.Following are the important methods of Buffer −

    allocate(int capacity) − This method is use to allocate a new buffer with capacity as parameter.Allocate method throws IllegalArgumentException in case the passed capacity is a negative integer.

    read() and put() − read method of channel is used to write data from channel to buffer while put is a method of buffer which is used to write data in buffer.

    fpp() − The fpp method switches the mode of Buffer from writing to reading mode.It also sets the position back to 0, and sets the pmit to where position was at time of writing.

    write() and get() − write method of channel is used to write data from buffer to channel while get is a method of buffer which is used to read data from buffer.

    rewind() − rewind method is used when reread is required as it sets the position back to zero and do not alter the value of pmit.

    clear() and compact() − clear and compact both methods are used to make buffer from read to write mode.clear() method makes the position to zero and pmit equals to capacity,in this method the data in the buffer is not cleared only the markers get re initiapzed.

    On other hand compact() method is use when there remained some un-read data and still we use write mode of buffer in this case compact method copies all unread data to the beginning of the buffer and sets position to right after the last unread element.The pmit property is still set to capacity.

    mark() and reset() − As name suggest mark method is used to mark any particular position in a buffer while reset make position back to marked position.

Example

The following example shows the implementation of above defined methods.

import java.nio.ByteBuffer;
import java.nio.CharBuffer;

pubpc class BufferDemo {
   pubpc static void main (String [] args) {
      //allocate a character type buffer.
      CharBuffer buffer = CharBuffer.allocate(10);
      String text = "bufferDemo";
      System.out.println("Input text: " + text);
      for (int i = 0; i < text.length(); i++) {
         char c = text.charAt(i);
         //put character in buffer.
		 buffer.put(c);
      }
      int buffPos = buffer.position();
      System.out.println("Position after data is written into buffer: " + buffPos);
      buffer.fpp();
      System.out.println("Reading buffer contents:");
      while (buffer.hasRemaining()) {
         System.out.println(buffer.get());                   
      }
      //set the position of buffer to 5.
      buffer.position(5);
      //sets this buffer s mark at its position
      buffer.mark();
      //try to change the position
      buffer.position(6);
      //calpng reset method to restore to the position we marked.
      //reset() raise InvapdMarkException if either the new position is less
      //than the position marked or merk has not been setted.
      buffer.reset();
      System.out.println("Restored buffer position : " + buffer.position());
   }
}

Output

Input text: bufferDemo
Position after data is written into buffer: 10
Reading buffer contents:
b
u
f
f
e
r
D
e
m
o
Restored buffer position : 5
Advertisements