【问题标题】:Bufferunderflowexception Java缓冲区下溢异常 Java
【发布时间】:2013-12-17 20:56:54
【问题描述】:

我正在将值写入文件。

值写正确。在另一个应用程序中,我可以毫无例外地读取文件。

但在我的新应用程序中,我在尝试读取文件时收到 Bufferunderflowexception

bufferunderflowexception 指的是:

Double X1 = mappedByteBufferOut.getDouble(); //8 byte (double)

这是我读取文件的代码:

 @Override
    public void paintComponent(Graphics g) {

    RandomAccessFile randomAccessFile = null;
    MappedByteBuffer mappedByteBufferOut = null;
    FileChannel fileChannel = null;

    try {
        super.paintComponent(g);

        File file = new File("/home/user/Desktop/File");

        randomAccessFile = new RandomAccessFile(file, "r");

        fileChannel = randomAccessFile.getChannel();

        mappedByteBufferOut = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length());

        while (mappedByteBufferOut.hasRemaining()) {
          
            Double X1 = mappedByteBufferOut.getDouble(); //8 byte (double)
            Double Y1 = mappedByteBufferOut.getDouble();
            Double X2 = mappedByteBufferOut.getDouble();
            Double Y2 = mappedByteBufferOut.getDouble();
            int colorRGB = mappedByteBufferOut.getInt(); //4 byte (int)
            Color c = new Color(colorRGB);

            Edge edge = new Edge(X1, Y1, X2, Y2, c);

            listEdges.add(edge);

        }
        repaint();

        for (Edge ed : listEdges) {
            g.setColor(ed.color);
            ed = KochFrame.edgeAfterZoomAndDrag(ed);
            g.drawLine((int) ed.X1, (int) ed.Y1, (int) ed.X2, (int) ed.Y2);
        }
    }
    catch (IOException ex)
    {
        System.out.println(ex.getMessage());
    }
    finally
    {
        try
        {
            mappedByteBufferOut.force();
            fileChannel.close();
            randomAccessFile.close();
            listEdges.clear();
        } catch (IOException ex)
        {
            System.out.println(ex.getMessage());
        }
    }
}

【问题讨论】:

  • if (randomAccessFile.length()>8){ while (mappedByteBufferOut.hasRemaining()) { } }

标签: java exception paintcomponent filechannel bufferunderflowexception


【解决方案1】:

来自java.nio.ByteBuffer的docs

抛出: BufferUnderflowException - 如果此缓冲区中剩余的字节数少于 8 个

我认为这很清楚这是 Exception 的来源。为了修复它,您需要通过检查remaining() 而不是只检查一个字节的hasRemaining() 来确保 ByteBuffer 中有足够的数据以便读取双精度(8 个字节):

while (mappedByteBufferOut.remaining() >= 36) {//36 = 4 * 8(double) + 1 * 4(int)

【讨论】:

    【解决方案2】:

    当你可以使用double时,我不会使用Double

    我怀疑你的问题是你在循环开始时有剩余字节,但你没有检查有多少字节并且不够。

    我还会确保您具有正确的字节字节序,默认为大字节序。

    【讨论】:

    • 将 Double 更改为 double,谢谢。当有足够的字节时,我应该怎么做才能继续循环?
    • 你即将读取36个字节,可以查看remaining() >= 36
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多