ByteBuffer写入数组BufferUnderflowException异常

艾姆喔替 2012-01-20 11:23:18
chf是前文的一个FileChannel

ByteBuffer buf = ByteBuffer.allocate(50);
chf.read(buf);
buf.flip();
byte [] byt = new byte[100];
buf.get(byt);
然后就出来了 :
Exception in thread "main" java.nio.BufferUnderflowException
at java.nio.HeapByteBuffer.get(Unknown Source)
at java.nio.ByteBuffer.get(Unknown Source)
at Sample.main(Sample.java:22)

请问这怎么办
...全文
5109 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
lost_guy_in_scut 2012-01-20
  • 打赏
  • 举报
回复
少一段代码,忘记关闭了。

public static void main(String[] args) throws IOException{
FileChannel channel = new FileOutputStream("D:/a.txt").getChannel();
// 字节方式写入
channel.write(ByteBuffer.wrap("hello, NIO world in java!".getBytes()));
channel.close();

// 根据FileInputStream获得通道FileChannel
channel = new FileInputStream("D:/a.txt").getChannel();
// ByteBuffer分配空间,16个字节
// 这里需要知道 byte是1字节, short和char是2字节,int和float是4字节
// long和double是8字节 1byte=8bit 。 基本只是还是必须记住的。
ByteBuffer buff = ByteBuffer.allocate(16);
// 字节数组数据装入buff,
channel.read(buff);
// 反转此缓冲区
buff.flip();
byte [] byt = new byte[10];
System.out.println(buff.get(byt));
channel.close();
}

lost_guy_in_scut 2012-01-20
  • 打赏
  • 举报
回复


ByteBuffer buf = ByteBuffer.allocate(50); //这里要改大
chf.read(buf); //这句话抛的异常
buf.flip();
byte [] byt = new byte[100];
buf.get(byt);

参考如下代码

public static void main(String[] args) throws IOException{
FileChannel channel = new FileOutputStream("D:/a.txt").getChannel();
// 字节方式写入
channel.write(ByteBuffer.wrap("hello, NIO world in java!".getBytes()));
channel.close();

// 根据FileInputStream获得通道FileChannel
channel = new FileInputStream("D:/a.txt").getChannel();
// ByteBuffer分配空间,16个字节
// 这里需要知道 byte是1字节, short和char是2字节,int和float是4字节
// long和double是8字节 1byte=8bit 。 基本只是还是必须记住的。
ByteBuffer buff = ByteBuffer.allocate(16);
// 字节数组数据装入buff,
channel.read(buff);
// 反转此缓冲区
buff.flip();
byte [] byt = new byte[10];
System.out.println(buff.get(byt)); // 根据FileOutputStream获得通道FileChannel
}
艾姆喔替 2012-01-20
  • 打赏
  • 举报
回复
我知道那个 改过 ByteBuffer 跟 byte的大小
不管谁大谁小 都出那个异常
MiceRice 2012-01-20
  • 打赏
  • 举报
回复
你的ByteBuffer才50,但是你buf.get(byt)这里面的字节数组长度是100,ByteBuffer表示它搞不定了。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧