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

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

问题描述

我解决了这个问题,我忘了关闭 ObjectOutputStream.'嗬!我会留下这个问题,以防万一有人想提出一个更优雅的选择,我们将不胜感激.

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.

我目前正在尝试将一个名为 phonebook 的类写入文件,其中包含一个名为 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天全站免登陆