我刚申请i/o,所以如果这是个很糟糕的问题,我很抱歉。
目前,我有一个add方法/main方法和一个person类,我的输出流在add方法中工作得很好:这是方法的顶部。
FileOutputStream myFile = null;
try {
myFile = new FileOutputStream("txt123.txt");
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(myFile);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}然后我使用了两次,因为有两种类型的人可以添加
oos.writeObject(person);
oos.close();
System.out.println("Done");因此,我的问题是,如何使输入工作,最后,在add方法或主方法中,我阅读了如何完成我在这里所做的工作:http://www.mkyong.com/java/how-to-write-an-object-to-file-in-java/
他也有一本关于在物体中阅读的指南,但我似乎无法让它发挥作用。
发布于 2012-11-02 03:11:06
您可以按照以下方式将ObjectOutputStream与FileOutputStream组合起来。我还猜您需要将读/写代码放在一个地方,以便允许重用。下面是一个使用DAO中的读/写的简单示例。
public static class Person implements Serializable {
private String name;
public Person(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return name;
}
}
public static class PersonDao {
public void write(Person person, File file) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(file));
oos.writeObject(person);
oos.close();
}
public Person read(File file) throws IOException,
ClassNotFoundException {
ObjectInputStream oos = new ObjectInputStream(new FileInputStream(
file));
Person returnValue = (Person) oos.readObject();
oos.close();
return returnValue;
}
}
public static void main(String[] args) throws IOException,
ClassNotFoundException {
PersonDao personDao = new PersonDao();
Person alice = new Person("alice");
personDao.write(alice, new File("alice.bin"));
Person bob = new Person("bob");
personDao.write(bob, new File("bob.bin"));
System.out.println(personDao.read(new File("alice.bin")));
System.out.println(personDao.read(new File("bob.bin")));
}https://stackoverflow.com/questions/13188691
复制相似问题