Bufferunderflowexception Java

 手机用户2602889207 发布于 2023-02-09 18:19

我正在写一个文件的值.

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

但是在我的新应用程序中,我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());
        }
    }
}

我希望有一个人可以帮助我.

1 个回答
  • 来自java.nio.ByteBuffer 的文档:

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

    我认为这很清楚,这是Exception的来源.为了解决这个问题,你需要确保ByteBuffer中有足够的数据来读取double(8个字节)而不是hasRemaining(),它只检查一个字节:

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

    2023-02-09 18:22 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有