如何将 Java 序列化对象写入和读取到文件中

2022-08-31 14:29:33

我将向一个文件写入多个对象,然后在代码的另一部分中检索它们。我的代码没有错误,但它不能正常工作。你能帮我找到我的代码有什么问题吗?我从不同的网站读取不同的代码,但没有一个对我有用!

以下是我将对象写入文件的代码:MyClassList是一个数组列表,其中包含我的类的对象(必须写入文件)。

for (int cnt = 0; cnt < MyClassList.size(); cnt++) {
    FileOutputStream fout = new FileOutputStream("G:\\address.ser", true);
    ObjectOutputStream oos = new ObjectOutputStream(fout);
    oos.writeObject(MyClassList.get(cnt));
}

我在输出流的构造函数中添加了“true”,因为我想将每个对象添加到文件的末尾。这是对的吗?

这是我从文件中读取对象的代码:

 try {
     streamIn = new FileInputStream("G:\\address.ser");
     ObjectInputStream objectinputstream = new ObjectInputStream(streamIn);
     MyClass readCase = (MyClass) objectinputstream.readObject();
     recordList.add(readCase);
     System.out.println(recordList.get(i));
 } catch (Exception e) {
     e.printStackTrace();
 }

它最终只打印出一个对象。现在,我不知道我是没有正确书写还是阅读正确!


答案 1

为什么不一次序列化整个列表呢?

FileOutputStream fout = new FileOutputStream("G:\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(MyClassList);

当然,假设 MyClassList 是一个 or ,或者是另一个集合。ArrayListLinkedListSerializable

在读回它的情况下,在你的代码中你只准备了一个项目,没有循环来收集所有写入的项。


答案 2

正如其他人所建议的那样,您可以一次序列化和反序列化整个列表,这更简单,并且似乎完全符合您打算执行的操作。

在这种情况下,序列化代码变为

ObjectOutputStream oos = null;
FileOutputStream fout = null;
try{
    fout = new FileOutputStream("G:\\address.ser", true);
    oos = new ObjectOutputStream(fout);
    oos.writeObject(myClassList);
} catch (Exception ex) {
    ex.printStackTrace();
} finally {
    if(oos != null){
        oos.close();
    } 
}

反序列化变为(假设 myClassList 是一个列表,并希望你使用泛型):

ObjectInputStream objectinputstream = null;
try {
    FileInputStream streamIn = new FileInputStream("G:\\address.ser");
    objectinputstream = new ObjectInputStream(streamIn);
    List<MyClass> readCase = (List<MyClass>) objectinputstream.readObject();
    recordList.add(readCase);
    System.out.println(recordList.get(i));
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if(objectinputstream != null){
        objectinputstream .close();
    } 
}

您还可以反序列化文件中的多个对象,就像您希望的那样:

ObjectInputStream objectinputstream = null;
try {
    streamIn = new FileInputStream("G:\\address.ser");
    objectinputstream = new ObjectInputStream(streamIn);
    MyClass readCase = null;
    do {
        readCase = (MyClass) objectinputstream.readObject();
        if(readCase != null){
            recordList.add(readCase);
        } 
    } while (readCase != null)        
    System.out.println(recordList.get(i));
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if(objectinputstream != null){
        objectinputstream .close();
    } 
}

请不要忘记在 finally 子句中关闭流对象(注意:它可以引发异常)。

编辑

正如注释中建议的那样,最好使用 try with 资源,并且代码应该变得非常简单。

以下是列表序列化:

try(
    FileOutputStream fout = new FileOutputStream("G:\\address.ser", true);
    ObjectOutputStream oos = new ObjectOutputStream(fout);
){
    oos.writeObject(myClassList);
} catch (Exception ex) {
    ex.printStackTrace();
}