0
How to store the value of a variable in java after the end of the program
1
For this, you can use a Serializable .
In this case, you must create a file to store the information you want to save.
Here’s a simple example of how to record and retrieve an object.
This file will be saved to the application root.
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;
}
}
Browser other questions tagged java
You are not signed in. Login or sign up in order to post.
You can store it in a txt file or in a bd
– DiegoAugusto
There’s not some kind of variable that does that for me in java?
– Marcos
The program will be terminated right?
– DiegoAugusto
It has a little more difficult way, here is a tutorial. See help: http://www.tutorialspoint.com/java/java_serialization.htm
– DiegoAugusto
if I intended right the question .. I intend to store something even with the program closed .. type a user’s login and password is that??? if there is a sharedpreferences look at this link http://answall.com/questions/128030/android-sharedpreferences-com-radiobutton/128109?noredirect=1#comment267161_128109
– Tiago
@Tiago, **sharedpreferences** would be for Android, right?
– Thiago Luiz Domacoski