在Java中反序列化文件中的对象 [英] De-serializing objects from a file in Java

查看:181
本文介绍了在Java中反序列化文件中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含XYZ类的多个序列化对象的文件。在序列化时,每个XYZ对象都附加到文件中。

I have a file which contains multiple serialized objects of class XYZ. While serializing, the each XYZ object was appended to the file.

现在我需要从文件中读取每个对象,并且我只能读取第一个对象。

Now I need to read each object from the file, and I am able to read only the first object.

我知道如何从文件中读取每个对象并最终将其存储到List中吗?

Any idea how I can read each object from the file and eventually store it into a List?

推荐答案

尝试以下方法:

List<Object> results = new ArrayList<Object>();
FileInputStream fis = new FileInputStream("cool_file.tmp");
ObjectInputStream ois = new ObjectInputStream(fis);

try {
    while (true) {
        results.add(ois.readObject());
    }
} catch (OptionalDataException e) {
    if (!e.eof) 
        throw e;
} finally {
    ois.close();
}

跟进Tom的精彩评论,多个 ObjectOutputStream s将是,

Following up on Tom's brilliant comment, the solution for multiple ObjectOutputStreams would be,

public static final String FILENAME = "cool_file.tmp";

public static void main(String[] args) throws IOException, ClassNotFoundException {
    String test = "This will work if the objects were written with a single ObjectOutputStream. " +
            "If several ObjectOutputStreams were used to write to the same file in succession, " +
            "it will not. – Tom Anderson 4 mins ago";

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(FILENAME);
        for (String s : test.split("\\s+")) {
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(s);
        }
    } finally {
        if (fos != null)
            fos.close();
    }

    List<Object> results = new ArrayList<Object>();

    FileInputStream fis = null;
    try {
        fis = new FileInputStream(FILENAME);
        while (true) {
            ObjectInputStream ois = new ObjectInputStream(fis);
            results.add(ois.readObject());
        }
    } catch (EOFException ignored) {
        // as expected
    } finally {
        if (fis != null)
            fis.close();
    }
    System.out.println("results = " + results);
}

这篇关于在Java中反序列化文件中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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