Java Nio 简明教程
Java NIO - Buffer
Java NIO 中的缓冲区可以看作一个简单的对象,它充当定大小数据块的容器,可用于向通道写入数据或从通道读取数据,以便缓冲区充当通道的端点。
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.
与经典 IO 相比,缓冲区使得 NIO 包更有效率且更快速,因为在 IO 的情况下,数据是以流的形式处理的,不支持异步和并发的数据流。此外,IO 也不允许以块或字节组的形式执行数据。
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.
定义 Java NIO 缓冲区的主要参数可以定义为:
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 limit 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 缓冲区可以根据缓冲区处理的数据类型进行以下分类:
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
如前所述,Buffer 充当内存对象,它提供了一组方法,使处理内存块更加方便。以下是 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.
-
flip() − The flip method switches the mode of Buffer from writing to reading mode.It also sets the position back to 0, and sets the limit 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 limit.
-
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 limit equals to capacity,in this method the data in the buffer is not cleared only the markers get re initialized. 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 limit 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;
public class BufferDemo {
public 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.flip();
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);
//calling reset method to restore to the position we marked.
//reset() raise InvalidMarkException 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());
}
}