import java.nio.IntBuffer;
public class NioTest
{
public static void main(String args[])
{
IntBuffer buf = IntBuffer.allocate(10); // 准备出10个大小的缓冲区
System.out.print("1、写入数据之前的position、limit和capacity:");
System.out.println("position = " + buf.position() + ",limit = " + buf.limit() + ",capacty = " + buf.capacity());
int temp[] = { 5, 7, 9 };// 定义一个int数组
buf.put(3); // 设置一个数据
buf.put(temp); // 此时已经存放了四个记录
System.out.print("2、写入数据之后的position、limit和capacity:");
System.out.println("position = " + buf.position() + ",limit = " + buf.limit() + ",capacty = " + buf.capacity());
buf.flip(); // 重设缓冲区
// postion = 0 ,limit = 原本position
System.out.print("3、准备输出数据时的position、limit和capacity:");
System.out.println("position = " + buf.position() + ",limit = " + buf.limit() + ",capacty = " + buf.capacity());
System.out.print("缓冲区中的内容:");
while (buf.hasRemaining())
{
int x = buf.get();
System.out.print(x + "、");
}
}
}
</pre><pre code_snippet_id="1558424" snippet_file_name="blog_20160117_1_2356753" name="code" class="java">import java.nio.IntBuffer;
public class NioTest
{
public static void main(String args[])
{
IntBuffer buf = IntBuffer.allocate(10); // 准备出10个大小的缓冲区
IntBuffer sub = null; // 定义子缓冲区
for (int i = 0; i < 10; i++)
{
buf.put(2 * i + 1); // 在主缓冲区中加入10个奇数
}
// 需要通过slice() 创建子缓冲区
buf.position(2);
buf.limit(6);
sub = buf.slice();
for (int i = 0; i < sub.capacity(); i++)
{
int temp = sub.get(i);
sub.put(temp - 1);
}
//// flip方法将Buffer从写模式切换到读模式。调用flip()方法会将position设回0,并将limit设置成之前position的值。
buf.flip(); // 重设缓冲区
buf.limit(buf.capacity());
System.out.print("主缓冲区中的内容:");
while (buf.hasRemaining())
{
int x = buf.get();
System.out.print(x + "、");
}
}
}
import java.nio.IntBuffer;
public class NioTest
{
public static void main(String args[])
{
IntBuffer buf = IntBuffer.allocate(10); // 准备出10个大小的缓冲区
IntBuffer read = null; // 定义子缓冲区
for (int i = 0; i < 10; i++)
{
buf.put(2 * i + 1); // 在主缓冲区中加入10个奇数
}
read = buf.asReadOnlyBuffer();// 创建只读缓冲区
read.flip(); // 重设缓冲区
System.out.print("主缓冲区中的内容:");
while (read.hasRemaining())
{
int x = read.get();
System.out.print(x + "、");
}
read.put(30); // 修改,错误
}
}