How to write and read java serialized objects into a file

前端 未结 5 1909
既然无缘
既然无缘 2020-11-27 03:13

I am going to write multiple objects to a file and then retrieve them in another part of my code. My code has no error, but it is not working properly. Could you please help

5条回答
  •  渐次进展
    2020-11-27 03:32

    if you serialize the whole list you also have to de-serialize the file into a list when you read it back. This means that you will inevitably load in memory a big file. It can be expensive. If you have a big file, and need to chunk it line by line (-> object by object) just proceed with your initial idea.

    Serialization:

    LinkedList listOfObjects = ;
    try {
        FileOutputStream file = new FileOutputStream();
        ObjectOutputStream writer = new ObjectOutputStream(file);
        for (YourObject obj : listOfObjects) {
            writer.writeObject(obj);
        }
        writer.close();
        file.close();
    } catch (Exception ex) {
        System.err.println("failed to write " + filePath + ", "+ ex);
    }
    

    De-serialization:

    try {
        FileInputStream file = new FileInputStream();
        ObjectInputStream reader = new ObjectInputStream(file);
        while (true) {
            try { 
                YourObject obj = (YourObject)reader.readObject();
                System.out.println(obj)
            } catch (Exception ex) {
                System.err.println("end of reader file ");
                break;
            }
        }
    } catch (Exception ex) {
        System.err.println("failed to read " + filePath + ", "+ ex);
    }
    

提交回复
热议问题