首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ObjectInputStream[Java]

ObjectInputStream[Java]
EN

Stack Overflow用户
提问于 2012-11-02 03:00:24
回答 1查看 96关注 0票数 0

我刚申请i/o,所以如果这是个很糟糕的问题,我很抱歉。

目前,我有一个add方法/main方法和一个person类,我的输出流在add方法中工作得很好:这是方法的顶部。

代码语言:javascript
复制
       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();
        }

然后我使用了两次,因为有两种类型的人可以添加

代码语言:javascript
复制
oos.writeObject(person);
oos.close();
System.out.println("Done");

因此,我的问题是,如何使输入工作,最后,在add方法或主方法中,我阅读了如何完成我在这里所做的工作:http://www.mkyong.com/java/how-to-write-an-object-to-file-in-java/

他也有一本关于在物体中阅读的指南,但我似乎无法让它发挥作用。

  • 谢谢!
EN

回答 1

Stack Overflow用户

发布于 2012-11-02 03:11:06

您可以按照以下方式将ObjectOutputStream与FileOutputStream组合起来。我还猜您需要将读/写代码放在一个地方,以便允许重用。下面是一个使用DAO中的读/写的简单示例。

代码语言:javascript
复制
 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")));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13188691

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档