在Java中反序列化文件中的对象

top*_*ard 5 java serialization deserialization

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

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

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

alf*_*alf 11

请尝试以下方法:

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();
}
Run Code Online (Sandbox Code Playgroud)

接下来汤姆的精彩评论,多个ObjectOutputStreams 的解决方案将是,

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果使用单个`ObjectOutputStream`编写对象,这将起作用.如果几个`ObjectOutputStream用于连续写入同一个文件,则不会. (6认同)