java.nio.BufferOverflowException问题

java.nio.BufferOverflowException问题

chuxiwen 5,060 2022-06-17

NIO相关异常

public static void main(String[] args) throws Exception {
        //创建一个输出流
        FileOutputStream fileOutputStream = new FileOutputStream("1.txt");
        //得到一个管道
        FileChannel channel = fileOutputStream.getChannel();
        //创建一个byte缓冲区
        ByteBuffer allocate = ByteBuffer.allocate(1024);
        while(true){
            //从控制台获取字符串
            Scanner in =new Scanner(System.in);
            //字符串赋予a
            String a = in.next();
            if ("exit".equals(a))
                break;
            //在缓冲区中放入a
            allocate.put(a.getBytes());
            //切换缓冲区的读写状态
            allocate.flip();
            //将缓冲区中的数据写入管道中
            channel.write(allocate);
        }
        channel.close();
        fileOutputStream.close();
    }

代码运行出现下面报错
在这里插入图片描述


翻阅源码后发现错误
在这里插入图片描述
在这里插入图片描述

代码中使用了flip()方法,将limit值从缓冲区总大小变成输入字符串大小,
channel.write(allocate)使position再次等于limit,
所以再次循环程序,position大于limit,所以抛出异常

图片理解:
在这里插入图片描述
position大于等于limit时抛出异常
在这里插入图片描述

解决办法:

使用allocate.clear()
在这里插入图片描述
allocate.clear()将limit和position初始化,就不会出现position大于limit的情况,除非传入字符串大于capacity,即缓冲区的大小

Scanner in =new Scanner(System.in);
            //字符串赋予a
            String a = in.next();
            if ("exit".equals(a))
                break;
            //在缓冲区中放入a
            allocate.put(a.getBytes());
            //切换缓冲区的读写状态
            allocate.flip();
            //将缓冲区中的数据写入管道中
            channel.write(allocate);
            //将缓冲区恢复初始值  恢复limit值
            allocate.clear();

总结:

出现这个异常,在程序适合处加入allocate.clear()方法就行!!!

备注:csdn用户狗贼是我个人


# Java 学习