java.nio.BufferUnderflowException 分析

  在写一个简单的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()方法每次获取一个字节

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值