Search code examples
javastatestorerestore

Store/Restore snapshot/state of entire application


I want to store the entire application state and then restore it on the next start. Is there a library which would make it easier for me? Or does anyone of you have any suggestions?

Standalone Application


Solution

  • There is a design pattern that is used for your purpouse, and it is the Memento Pattern.

    The memento pattern is implemented with three objects: the originator, a caretaker and a memento. The originator is some object that has an internal state. The caretaker is going to do something to the originator, but wants to be able to undo the change. The caretaker first asks the originator for a memento object. Then it does whatever operation (or sequence of operations) it was going to do. To roll back to the state before the operations, it returns the memento object to the originator. The memento object itself is an opaque object (one which the caretaker cannot, or should not, change). - Wikipedia

    You can read the example provided in the wiki page to understand how to use it inside your code.

    If you want to save the state of an object as a file, and have it avaiable even after the execution of your program is over, you should implement the Serializable interface in the class you want to store.

    Example:

    public class Example implements Serializable
        {
    
        }
    

    and where you instantiate that class:

    try{
    
        Example c = new Example();
        FileOutputStream fout = new FileOutputStream("YOURPATH");
        ObjectOutputStream oos = new ObjectOutputStream(fout);   
        oos.writeObject(c);
        oos.close();
        System.out.println("Done");
    
       }catch(Exception ex){
           ex.printStackTrace();
       }