写非字符串对象的ArrayList到文件 [英] Writing an ArrayList of non-string objects to file

查看:146
本文介绍了写非字符串对象的ArrayList到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我的问题解决了,我忘了关闭的ObjectOutputStream。 卫生署!我将离开,以防万一有人想提出一个更优雅的选择,这将是非常美联社preciated的问题。

I solved the problem, I forgot to close the ObjectOutputStream. 'doh! I'll leave the question just in case someone wants to propose a more elegant option, which would be much appreciated.

我现在想写一个名为电话簿为文件类,它包含一个名为PhonebookEntry对象的ArrayList。这里是电话簿类:

I currently am trying to write a class called phonebook to file, which contains an ArrayList of objects called PhonebookEntry. Here is the Phonebook class:

import java.util.ArrayList;
import java.io.*;

public class Phonebook implements Serializable
    private static final long serialVersionUID = 1;

    ArrayList<PhonebookEntry> phonebookEntries = new ArrayList<PhonebookEntry>();

    public void addEntry(String name, String number) {
        PhonebookEntry newEntry = new PhonebookEntry(name, number);
        phonebookEntries.add(newEntry);
    }

}

我已经使用一个简单的ObjectInput / OutputStream的尝试,我可以得到它保存方式,但不加载(通常与EOFExcpetion)。有一种优雅的方式来保存这样一个对象,或者是有什么办法对象的ArrayList保存到一个文件?

I have tried using a simple ObjectInput/OutputStream and I can get it to save that way, but not to load (usually with an EOFExcpetion). Is there an elegant way to save an object like this, or is there any way to save an ArrayList of objects to a file?

推荐答案

下面的作品。我猜你错过的flush()或close()。

The following works. I'm guessing you're missing flush() or close().

public static void main(final String[] args) throws IOException, ClassNotFoundException {
    final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test.out"));
    final Phonebook phonebook = new Phonebook();
    out.writeObject(phonebook);
    out.flush();
    out.close();

    final ObjectInputStream in = new ObjectInputStream(new FileInputStream("test.out"));
    final Object o = in.readObject();
    System.out.println(o);
}

这篇关于写非字符串对象的ArrayList到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆