Reputation: 205
I want to save a file "xp.txt" to keep track of the user's experience in a game. If the file doesn't exist, I'd like to create it and write "0" in the file (to indicate 0 experience). If the file exists I'd like to read from it and save the exp to an int variable in the java class. And I'd also like to know how to change the value from "0" to some other value.
Thanks in advance!
My current code is:
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(XP, 0));
out.write("0");
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
InputStream in = openFileInput(XP);
if (in != null) {
InputStreamReader temp = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(temp);
String str;
StringBuilder buf = new StringBuilder();
while ((str = reader.readLine()) != null) {
xp = Integer.parseInt(str);
System.out.println(xp);
}
in.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But I cannot find the text file and it doesn't work as I intended.
Upvotes: 1
Views: 4697
Reputation: 5973
You can use the following ways to store data
I think for your use case SharedPreferences
will do good. A quick example would be
To Save a value :
SharedPreferences.Editor editor = getSharedPreferences("unique_name", MODE_PRIVATE).edit();
editor.putInt("xp", 10);
editor.commit();
To Retrieve value
SharedPreferences prefs = getSharedPreferences("unique_name", MODE_PRIVATE);
int xp = prefs.getInt("xp", 0); // will return 0 if no value is saved
You can read more from this here.
Upvotes: 2