流操作java.io.EOFException求解释

SmarkMeng 2012-02-11 09:57:24
错误:
Exception in thread "main" java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2554)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1297)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at Test.js(Test.java:37)
源程序:
public static Integer js() throws FileNotFoundException, IOException, ClassNotFoundException{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("num.txt"));
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("num.txt"));
Object o;
//oos.writeObject(new Integer(2));
Integer i = 0;
o = ois.readObject();
if(o instanceof Integer){
i = (Integer)o;
i++;
oos.writeObject(i);
}
return i;
}
加上红色的代码是可以,但注释掉后就抛出例外,在网上找了很多文章,可还是解释不通,求高手赤脚。。。。。。
...全文
7078 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
-冷落清秋- 2014-08-21
  • 打赏
  • 举报
回复
SmarkMeng 2012-02-11
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 alexandertech 的回复:]

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("num.txt"));
不论之前num.txt中是否有内容,这行代码会把num.txt截短成4个字节,准备后续的写入。
此时,如果没有oos.writeObject()来先写入一个Object到文件中,ois.readObject()是读不到内容的,不但……
[/Quote]
嗯 了解了 thanks
飞跃颠峰 2012-02-11
  • 打赏
  • 举报
回复
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("num.txt"));
不论之前num.txt中是否有内容,这行代码会把num.txt截短成4个字节,准备后续的写入。
此时,如果没有oos.writeObject()来先写入一个Object到文件中,ois.readObject()是读不到内容的,不但读不到,而且会抛出EOFException,因为一直读到文件尾部预想的内容也没出现。
而如果先执行了oos.writeObject(),则文件中已经有了内容,自然ois.readObject()就能顺利执行不报异常了。
SmarkMeng 2012-02-11
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 wlianghe00 的回复:]

有没有实现serializable接口?
[/Quote]
你是指哪个类啊? 写入的是Integer啊
Utopia 2012-02-11
  • 打赏
  • 举报
回复
有没有实现serializable接口?

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧