
java新IO之IntBuffer
1 : put方法,position方法,limit方法,capacity方法
public abstract IntBuffer put(int i)
相对 put 方法(可选操作)。
将给定 int 写入此缓冲区的当前位置,然后该位置递增。
参数:i - 要写入的 int
返回:此缓冲区
抛出: BufferOverflowException - 如果此缓冲区的当前位置不小于界限
ReadOnlyBufferException - 如果此缓冲区是只读的
下面是一个例子:
运行结果截图:
2、flip方法
public final Buffer flip()
反转此缓冲区。首先将限制设置为当前位置,然后将位置设置为 0。
package org.liuchao; import java.nio.*; public class IntBufferDemo { public static void main(String[] args) { // TODO Auto-generated method stub IntBuffer buf = IntBuffer.allocate(20);//设置缓冲区容量为20个大小 System.out.println("缓冲区写入数据之前:"); System.out.println(buf.capacity());//调用capacity方法返回buf容量 System.out.println(buf.position());//调用position方法返回buf的位置 System.out.println(buf.limit());//调用limit方法返回buf的限制 int temp[]={1,2,3,4}; int i = 0; buf.put(i);//写入i buf.put(temp);//写入数组temp System.out.println("缓冲区写入数据之后:"); System.out.println(buf.capacity());//调用capacity方法返回buf容量 System.out.println(buf.position());//调用position方法返回buf的位置 System.out.println(buf.limit());//调用limit方法返回buf的限制 System.out.println("缓冲区内容:"); buf.flip();//反转此缓冲区 //输出缓冲区内容 while(buf.hasRemaining()){ int x = buf.get();//相对 get 方法。读取此缓冲区当前位置的 int,然后该位置递增。 System.out.println(x); } } }
运行截图: