How to store the value of a variable in java after the end of the program
How to store the value of a variable in java after the end of the program
For this, you can use a Serializable .
In this case, you should create a file to store the information you want to save.
Here's a simple example of how to write and retrieve an object.
This file will be saved at the root of the application.
Follows:
private static final File FILE= new File("MyObject.obj");
/**
* Salva um Serializable
* @param object
* @throws IOException
*/
public static void save(MyObject object) throws IOException{
final FileOutputStream fileOutputStream = new FileOutputStream(FILE);
final ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(object);
objectOutputStream.close();
fileOutputStream.close();
}
/*
* Carrega o Serializable
*/
public static MyObject load() throws IOException, ClassNotFoundException{
final FileInputStream fileInputStream = new FileInputStream(FILE);
final ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
MyObject object = (MyObject)objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
return object;
}
/**
* Objeto de exemplo, para que seja salvo é necessário implementar um Serializable
*/
static class MyObject implements Serializable{
/**
* Serial é o identifica a versão da classe que será usada no processo de serializacão
*/
private static final long serialVersionUID = 1L;
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}