Answer the question
In order to leave comments, you need to log in
How can I make the value of the variable be automatically saved when the program ends?
How can I make sure that after the program is closed, the value of the variable is saved, and the next time it is started, the variable already has the same value when the program was last closed?
Answer the question
In order to leave comments, you need to log in
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();
}
}));
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question