当前位置: 代码网 > it编程>编程语言>Java > 关于java.io.EOFException产生的原因以及解决方案

关于java.io.EOFException产生的原因以及解决方案

2025年01月24日 Java 我要评论
java.io.eofexception产生的原因及解决异常发生场景使用objectinputstream类往文件中传入自定义类student时objectinputstream objectinpu

java.io.eofexception产生的原因及解决

异常发生场景

使用objectinputstream类往文件中传入自定义类student时

objectinputstream objectinputstream=null;
        arraylist<student> students=null;
        try {
            objectinputstream = new objectinputstream(new fileinputstream("d:\\桌面\\java38\\javase08\\java08\\1.txt"));
            students = (arraylist<student>) objectinputstream.readobject();
            system.out.println("数据载入成功");
​
        }catch (exception e) {
            e.printstacktrace();
            system.out.println("数据载入失败");
        }

异常产生原因

经过导师查找,终于发现了ofexception产生的原因

objectinputstream objectinputstream=null;
//idea上显示null为灰色,说明 new objectinputstream(new fileinputstream("d:\\桌面\\java38\\javase08\\java08\\1.txt"));返回值为null,即文件"d:\\桌面\\java38\\javase08\\java08\\1.txt"为空
objectinputstream = new objectinputstream(new fileinputstream("d:\\桌面\\java38\\javase08\\java08\\1.txt"));

objectinputstream为空值,则不能使用objectinputstream.close();如果使用会产生并发症 java.lang.nullpointerexception(空指针异常)

异常解决

        objectinputstream objectinputstream=null;
        arraylist<student> students=null;
        try {
            objectinputstream = new objectinputstream(new fileinputstream("d:\\桌面\\java38\\javase08\\java08\\1.txt"));
            students = (arraylist<student>) objectinputstream.readobject();
            system.out.println("数据载入成功");
​
        } catch (eofexception e) {
            students = new arraylist<>();
​
        }catch (exception e) {
            e.printstacktrace();
            system.out.println("数据载入失败");
        } finally {
            if(objectinputstream != null) {
                objectinputstream.close();
            }

在finally语句内加上判断,不等于空值才关闭

捕获eofexception,但不打印错误,为students,new一个新的集合(本来这里也有一个会出bug的地方,但是被我之前就给students赋了null值,(arraylist<student> students=null;)所以catch里new一个新的对象)

如果不为空,则

students = (arraylist<student>) objectinputstream.readobject();

正常执行,不报错误~

总结

java.io.eofexception不是一个常出现的问题,而且并发症 java.lang.nullpointerexception(空指针异常),只有objectinputstream.readobject();接收为null且1.txt文件为空时才会出现

eofexception只需要捕获,该bug在本场景下被捕获后程序就不会终止了,甚至不处理也行。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com