在项目电子商城中遇到了一个java.io.EOFException 异常。
(这个异常只是在这个项目中遇到了,这是我的解决方法,不代表遇到这个异常的所有情况都适用这个方法。)
public void FrmFile(){ File myfile = new File("User.txt"); try{ FileInPutStream fis = new FileInPutStream(myfile); ObjectInPutStream ois = new ObjectInPutSrtream(fis); user.List = ois.readObject(); //异常是在这步提出的。提出异常试音为当时User.txt刚刚建立,内容为空,ois读不到东西所以报出异常 fis.close(); ois.close(); } catch(Exception e){ e.printStackTrace; } }
解决方法有两个
1、暂时先不调用FromFile这个方法,因为文件里也没有东西,调不调用不影响,等把内容存都文件后,在调用这个方法,就不会报异常了。
2、加一个判断语句
public void FrmFile(){ File myfile = new File("User.txt"); try{ FileInPutStream fis = new FileInPutStream(myfile); if(myfile.length() == 0){ //如果是空的话就不要读了 fis.close(); return ; }else{ //不空的话就继续 ObjectInPutStream ois = new ObjectInPutSrtream(fis); user.List = ois.readObject(); ois.close(); fis.close(); } } catch(Exception e){ e.printStackTrace; } }