在写一个简单的Buffer的小例子的时候,抛出一个异常:
Exception in thread "main" java.nio.BufferUnderflowException
at java.nio.Buffer.nextGetIndex(Buffer.java:498)
at java.nio.HeapByteBuffer.getChar(HeapByteBuffer.java:253)
at com.malone.nio.BufferDemo.main(BufferDemo.java:22)
例子的代码为:
public class BufferDemo {
public static void main(String[] args) throws IOException {
RandomAccessFile file = new RandomAccessFile ("D:\\https.txt", "rw");
FileChannel fc = file.getChannel();
ByteBuffer b = ByteBuffer.allocate(64);
while (true) {
int readFlag = fc.read(b);
if (readFlag == -1) {
break;
}
b.flip();
while (b.hasRemaining()) {
System.out.println(b.getChar() + " " + b.position() + " " + b.remaining());
}
b.clear();
}
file.close();
}
}
根据异常定位,在打印Buffer里面的内容的时候报错的,仔细分析一下,猜想错误原因可能是:
调用getChar()方法,char的字符长度为2个字节,而ByteBuffer的remaining长度为1时,强行获取两个字节应该会抛出异常
基于以上思路,修改例子代码,把打印代码改为:
System.out.println(b.getChar() + " " + b.position() + " " + b.remaining());
控制台打印结构为:
쳡 44 20
쪾 46 18
ꎬ 48 16
듋 50 14
솴 52 12
뷓 54 10
늻 56 8
뿉 58 6
탅 60 4
죎 62 2
ꎬ 64 0
퓲 2 19
엤 4 17
훃 6 15
桴 8 13
瑰 10 11
玻 12 9
랾 14 7
뎳 16 5
즹 18 3
ꚣ 20 1
Exception in thread "main" java.nio.BufferUnderflowException
at java.nio.Buffer.nextGetIndex(Buffer.java:498)
at java.nio.HeapByteBuffer.getChar(HeapByteBuffer.java:253)
at com.malone.nio.BufferDemo.main(BufferDemo.java:22)
有控制台打印结果可以看出,每次从ByteBuffer的数组中每次取出两个字节来打印,并移动position的值,当移动到最后时,position和limit之间只有一个字节时,再试图获取两个字节时,就抛出了异常!
如果在打印ByteBuffer里的内容时,使用ByteBuffer的get()方法,就不会出现上面的问题,get()方法每次获取一个字节