作者在 2011-12-10 22:26:25 发布以下内容
下面的例子演示了如何用 ByteBuffer(字节缓冲区)来存储字符。有时候程序可能会希望在将字符串存至文件时不用来回进行字符到字节间的(显式)转换。下面的例子首先在 ByteBuffer 上创建一个字符视图(即 CharBuffer ,字节缓冲区),CharBuffer中有用来提供读、写字符串的方法。
这个例子并没有将字符和字节进行转换。对于如何在字符和字节之间进行转换,后文将给出例子。
// 获得一个ByteBuffer对象
ByteBuffer buf = ByteBuffer.allocate(100);
// 创建一个character ByteBuffer
CharBuffer cbuf = buf.asCharBuffer();
// 写入一个字符串
cbuf.put("a string");
// 将 character ByteBuffer 转换到String
//字符串包含从position到limit的字符,所以先调用flip方法
cbuf.flip();
String s = cbuf.toString(); // "a string"
// 不会影响到position
// 获得一个子串
int start = 2; // start是相对于position的
int end = 5;
CharSequence sub = cbuf.subSequence(start, end); // "str"
ByteBuffer buf = ByteBuffer.allocate(100);
// 创建一个character ByteBuffer
CharBuffer cbuf = buf.asCharBuffer();
// 写入一个字符串
cbuf.put("a string");
// 将 character ByteBuffer 转换到String
//字符串包含从position到limit的字符,所以先调用flip方法
cbuf.flip();
String s = cbuf.toString(); // "a string"
// 不会影响到position
// 获得一个子串
int start = 2; // start是相对于position的
int end = 5;
CharSequence sub = cbuf.subSequence(start, end); // "str"