How to make shutdown programs have an automatic save value of a variable?

How to make so that after you close the program the value of the variable is preserved, and the next time you start the variable have that value, when it was closed the last time the program?
March 25th 20 at 13:28
1 answer
March 25th 20 at 13:30
Solution
public class Example {
 private static final String FILE_NAME = "state.dat";

 private int value;

 public void setValue(int value) {
 this.value = value;
}

 public int getValue() {
 return value;
}

 public static void main(String[] args) {
 Example obj = new Example();

 try (InputStream in = new FileInputStream(FILE_NAME)) {
obj.setValue(in.read());
 } catch (IOException exc) {
exc.printStackTrace();
}

 Runtime.getRuntime().addShutdownHook(new Thread(() -> {
 try (OutputStream out = new FileOutputStream(FILE_NAME)) {
out.write(obj.getValue());
 } catch (IOException exc) {
exc.printStackTrace();
}
}));
}
}

Find more questions by tags Java