首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用BufferUnderflowException和序列化时的Java

使用BufferUnderflowException和序列化时的Java
EN

Stack Overflow用户
提问于 2014-05-15 15:53:42
回答 1查看 7.2K关注 0票数 1

我试图编写一个程序,通过数据报通道使用Java发送和接收序列化对象,但当试图从BufferUnderFlow读取对象时,我收到了一个ObjectInputStream异常。

目前,我有以下代码:

发件人:

代码语言:javascript
复制
public void sendMessage(InetSocketAddress destination) {
    writeBuffer = ByteBuffer.allocate(64000);
    writeBuffer.clear();
    /*
     * Put new MyObject into a ByteArrayOutputStream and put that
     * into the writeBuffer to be sent.
     */
    MyObject myObject = new MyObject();
    byteArrayOS = new ByteArrayOutputStream(writeBuffer.capacity());
    objectOS = new ObjectOutputStream(byteArrayOS);
    objectOS.writeObject(myObject);
    objectOS.flush();

    writeBuffer.put(byteArrayOS.toByteArray());
    writeBuffer.flip();
    channel.send(writeBuffer, new InetSocketAddress(ipAddress, portNum));
    // Channel is bound to correct IP / Port
}

接受者:

代码语言:javascript
复制
public void read() {
  try { //blah blah
    channel = DatagramChannel.open();
    channel.socket().bind(new InetSocketAddress(readPort));
    channel.configureBlocking(true);

    ByteArrayInputStream byteArrayIS = null;
    ObjectInputStream objectIS = null;
    MyObject object;
    while (true) {
        inputBuffer.clear();
    client.getChannel().receive(inputBuffer);
    byte[] data = new byte[inputBuffer.capacity()];
    inputBuffer.get(data);
        /*
         * Troubleshooting: inputBuffer is returning with something
         */
        byteArrayIS = new ByteArrayInputStream(data);
        objectIS = new ObjectInputStream(byteArrayIS);
        myObject = objectIS.readObject(); // Throwing BufferUnderflowException here
        // Process object
        // ...
    }
  } catch (BlahBlah e) {}
}

这是我得到的例外:

代码语言:javascript
复制
Exception in thread "main" java.nio.BufferUnderflowException
        at java.nio.HeapByteBuffer.get(HeapByteBuffer.java:145)
        at java.nio.ByteBuffer.get(ByteBuffer.java:694)
        at package.Class.main(Class.java:493)

是什么导致抛出这个BufferUnderflowException?我搞不懂。两个ByteBuffers都分配了相同的空间,并且writeBuffer没有溢出。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-15 21:08:14

必须翻转()缓冲区才能从缓冲区中获取数据。注意,您应该在该行中使用极限(),而不是容量()。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23683187

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档