本帖最后由 月夜小楠 于 2014-12-30 12:23 编辑
- import java.io.*;
- class Person implements Serializable
- {
- private String name;
- String age;
- static String country = "cn";
- Person(String name,String age)
- {
- this.name = name;
- this.age = age;
- }
- public void setName(String name)
- {
- this.name = name;
- }
- public String getName()
- {
- return name;
- }
- public void setAge(String age)
- {
- this.age = age;
- }
- public String getAge()
- {
- return age;
- }
- public int hashCode()
- {
- return name.hashCode()+Integer.parseInt(age)*18;
- }
- public boolean equals(Object obj)
- {
- if (!(obj instanceof Person))
- {
- return false;
- }
- Person p = (Person)obj;
- return this.name.equals(p.name)&&this.age.equals(p.age);
- }
- public String toString()
- {
- return name+":"+age+":"+country;
- }
- }
- class ObjStreamDemo
- {
- public static void main(String[] args) throws IOException,ClassNotFoundException
- {
- writeObj();//将对象写入到person.txt文件中。
- readObj();//将person.txt文件中的对象打印到控制台上。
- }
- public static void readObj() throws IOException,ClassNotFoundException
- {
- ObjectInputStream ois = new ObjectInputStream(
- new FileInputStream("person.txt"));
- Object obj = null;
- while ((obj=ois.readObject())!=null )
- {
- if (!(obj instanceof Person))
- {
- throw new RuntimeException ("对象错误");
- }
- Person p = (Person) obj;
- System.out.println(p);
- }
- ois.close();
- }
- public static void writeObj() throws IOException
- {
- ObjectOutputStream oos = new ObjectOutputStream(
- new FileOutputStream("person.txt"));
- oos.writeObject(new Person("lisi","39"));
- oos.writeObject(new Person("wangwu","40"));
- oos.writeObject(new Person("sunliu","50"));
- oos.flush();
- oos.close();
- }
- }
复制代码
运行结果是正确的,但会报出以下异常:
Exception in thread "main" java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputSt
ream.java:2601)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1319)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
at ObjStreamDemo.readObj(ObjStreamDemo.java:58)
at ObjStreamDemo.main(ObjStreamDemo.java:51)
|