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); // 修改,錯誤
}
}