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在本场景下被捕获后程序就不会终止了,甚至不处理也行。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论