diff --git a/pom.xml b/pom.xml index 9eb33f6..da0d109 100644 --- a/pom.xml +++ b/pom.xml @@ -6,4 +6,12 @@ 1.0-SNAPSHOT Archetype - nioDemo http://maven.apache.org + + + org.junit.jupiter + junit-jupiter + RELEASE + compile + + diff --git a/src/doc/buffer.md b/src/doc/buffer.md new file mode 100644 index 0000000..2c6e179 --- /dev/null +++ b/src/doc/buffer.md @@ -0,0 +1,146 @@ +# Buffer +其中Position和Limit的含义取决于Buffer在read还是write模式 + +无论何种模式,Capacity含义不变 + +Buffer支持的类型 +- ByteBuffer +- MappedByteBuffer +- CharBuffer +- DoubleBuffer +- FloatBuffer +- IntBuffer +- LongBuffer +- ShortBuffer +![img.png](img/img.png) +## Capacity +内存块,Buffer的固定值 + +只能写入Byte,Long,Char等类型,若Buffer满了需要清除才能继续写数据 +## Position +写的时候代表写入数据当前位置,初始位置指向0,最大值为Capacity-1 + +读的时候代表读入数据当前位置,初始位置指向0 +## Limit +写数据时,Limit表示对Buffer最大写入多少容量,写模式下等于Capacity + +读数据时表示还有多少数据可读 +## 分配与写数据 +### 创建 + +```java +import java.nio.ByteBuffer; +import java.nio.CharBuffer; + +ByteBuffer buffer = ByteBuffer.allocate(48); +CharBuffer charBuffer=ByteBuffer.allocate(1024) +``` +### 写数据 +#### Channel +```java +int bytesRead = inChannel.read(buf); +//read into buffer +``` +#### put() +```java +buf.put(127); +``` +### flip() +切换读写模式 + +### 读数据 +#### Buffer +```java +int bytesWrite = inChannel.write(buf); +``` +#### get() +```java +byte aByte = buf.get(); +``` +## 常用方法 +### rewind() +position置零,重读buffer数据,limit不变 +### clear() compact() +clear直接清除 + +compact未读数据可继续读 +### mark() reset() +使用mark方法标记buffer中的一个特定position,通过reset()恢复这个position +## 缓冲区操作 +### 缓冲区分片 slice() +在现有buffer缓冲区中切分出一块新区域 +```java + public void bufferSlice(){ + ByteBuffer allocate = ByteBuffer.allocate(10); + for(int i=0;i