缓冲区下溢异常 Java

10

我正在将数值写入文件。

这些数值已经被正确地写入了。在另一个应用程序中,我可以读取文件而没有任何异常。

但是,在我的新应用程序中,尝试读取该文件时会出现 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());
        }
    }
}

如果(randomAccessFile.length()>8){ while (mappedByteBufferOut.hasRemaining()) { }} - ImGeorge
2个回答

10

根据java.nio.ByteBuffer的文档

如果在此缓冲区中剩余的字节小于八个,则抛出BufferUnderflowException异常。

我认为这很清楚地说明了这个异常是从哪里来的。要解决这个问题,您需要确保ByteBuffer中有足够的数据以读取一个double(8个字节),方法是使用remaining()而不是hasRemaining(),后者仅检查一个字节:

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

3

如果可以使用 double,我不会使用 Double

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

我还会确保你有正确的字节序,缺省是大端序。


将Double更改为double,谢谢。 当有足够的字节时,我应该怎么做才能继续循环? - Swag
您即将读取36个字节,您可以检查remaining()>=36 - Peter Lawrey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接