日期:2014-05-20 浏览次数:20825 次
import java.io.*; class Student implements Serializable{ private String name; public Student(String name){ this.name=name; } public String getName(){ return this.name; } public String toString(){ return "姓名:"+this.name; } } public class MyDemo{ public static void main(String[] args) throws IOException, ClassNotFoundException{ FileOutputStream fos=new FileOutputStream("m.dat"); ObjectOutputStream oos=new ObjectOutputStream(fos); oos.writeObject(new Student("ahah")); oos.writeObject(new Student("papa")); System.out.println("ok!"); oos.close(); fos.close(); // FileInputStream fis=new FileInputStream("m.dat"); ObjectInputStream ois=new ObjectInputStream(fis); while(ois.readObject()!=null){//这一行错了,是为什么? Student stu1=(Student)ois.readObject(); System.out.println(stu1); } ois.close(); fis.close(); } }
ok! 姓名:papa Exception in thread "main" java.io.EOFException at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2571) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1315) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369) at MyDemo.main(MyDemo.java:27)
public class MyDemo{ public static void main(String[] args) throws IOException, ClassNotFoundException{ FileOutputStream fos=new FileOutputStream("m.dat"); ObjectOutputStream oos=new ObjectOutputStream(fos); oos.writeObject(new Student("ahah")); oos.writeObject(new Student("papa")); System.out.println("ok!"); oos.close(); fos.close(); // FileInputStream fis=new FileInputStream("m.dat"); ObjectInputStream ois=new ObjectInputStream(fis); Student s; //定义Student类变量. while((fis.available()>0)&&(s= //判断是否到文件尾。 (Student)ois.readObject())!=null){ //Student stu1=(Student)ois.readObject(); //再运行就读了下一个了。 System.out.println(s); } ois.close(); fis.close(); } }