简体   繁体   中英

How to get java to save data when you exit a program

I am making a program with adding achievements to it. Im going to use some simple code to check if the Boolean is set to false before giving you the achievement private boolean hasAch1 = false; But whenever i close the application it set's the Boolean back to false, i was just wondering if there was a way to keep the Boolean set to true if you have received the achievement?

public static void main(String[] args) {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run(){
            //save data here
            System.out.println("Exiting");
        }
    });
}

But I don't recommend it as computers can crash and many other problems. It's best to autosave to a file every 5 minutes or so.

Write an external file every time you close your application and read it back when you open it. This way you can keep track of your variable.

http://www.javapractices.com/topic/TopicAction.do?Id=42

You can use Serialization to save the instance of your class to external file and next time you can read the file and Deserialize.

Here is the example you can refer to -

http://www.tutorialspoint.com/java/java_serialization.htm

If you want to maintain the state of an application, you have 2 options.

1. Serialize the data .

2.Save the data inside a database.

For a small application you can go for serialization. Coming to your question of saving the state while exiting , @WalterM has already answered that part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM