Java NIO 由以下几个核心部分组成:
传统的IO操作面向数据流,意味着每次从流中读一个或多个字节,直至完成,数据没有被缓存在任何地方。NIO操作面向缓冲区,数据从Channel读取到Buffer缓冲区,随后在Buffer中处理数据。本文着重介绍Channel和Buffer的概念以及在文件读写方面的应用和内部实现原理。
BufferA buffer is a linear, finite sequence of elements of a specific primitive type.
一块缓存区,内部使用字节数组存储数据,并维护几个特殊变量,实现数据的反复利用。
- mark:初始值为-1,用于备份当前的position
- position:初始值为0。position表示当前可以写入或读取数据的位置。当写入或读取一个数据后, position向前移动到下一个位置。
- limit:
写模式下,limit表示最多能往Buffer里写多少数据,等于capacity值。
读模式下,limit表示最多可以读取多少数据。 - capacity:缓存数组大小
Buffer.png
mark():把当前的position赋值给mark
public final Buffer mark() { mark = position; return this;}reset():把mark值还原给position
public final Buffer reset() { int m = mark; if (m < 0) throw new InvalidMarkException(); position = m; return this;}clear():一旦读完Buffer中的数据,需要让Buffer准备好再次被写入,clear会恢复状态值,但不会擦除数据。
public final Buffer clear() { position = 0; limit = capacity; mark = -1; return this;}flip():Buffer有两种模式,写模式和读模式,flip后Buffer从写模式变成读模式。
public final Buffer flip() { limit = position; position = 0; mark = -1; return this;}rewind():重置position为0,从头读写数据。
public final Buffer rewind() { position = 0; mark = -1; return this;}目前Buffer的实现类有以下几种:
- ByteBuffer
- CharBuffer
- DoubleBuffer
- FloatBuffer
- IntBuffer
- LongBuffer
- ShortBuffer
- MappedByteBuffer
其中MappedByteBuffer实现比较特殊,感兴趣的可以看看 深入浅出MappedByteBuffer
Paste_Image.png |