您的位置:首页 > 移动开发 > Objective-C

解决ObjectInputStream的readObject()方法的EOF异常

2015-10-21 15:48 453 查看
import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;

public class ObjectStream {

public static void main(String[] args) {

ObjectOutputStream oos = null;

ObjectInputStream ois = null;

Person pe = null;

try {

FileOutputStream out = new FileOutputStream(“D:/obj.txt”);

oos = new ObjectOutputStream(out);

Person per = new Person(“微软”, 14);

pe = new Person(“金山”, 20);

oos.writeObject(per);

oos.writeObject(pe);

oos.writeObject(null);//解决EOF的关键,加入一个空的对象

System.out.println(“添加成功”);

oos.close();

out.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

try{
FileInputStream in = new FileInputStream("D:/obj.txt");
ois = new ObjectInputStream(in);
Object obj=null;
while((obj=ois.readObject())!=null) {
Person s = (Person)obj;
System.out.println(s);
}
ois.close();
in.close();
} catch(Exception e) {
e.printStackTrace();
}
}


}

class Person implements Serializable {

private String name;

private /transient/ int age;

public Person(String name, int age) {
this.name = name;
this.age = age;
}

public String getNmae(){
return name;
}
public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String toString() {
return "姓名:" + name + "  性别:" + age;
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: