I am working on a game and I want to store the High score in a file and read it whenever it's needed. I wanted to use BufferedWriter and BufferedReader like this on the gameover class.
File fi = new File("score.txt");
BufferedWriter w = new BufferedWriter(new FileWriter(fi));
BufferedReader r = new BufferedReader(new FileReader(fi));
So whenever I get a score I will compare it to the score in the file and if the score is greater the score of the file I will store it to the file as a high score so the new high score will be updated in the file. But the problem is every time I run the program the score.txt got the null value, means it's not storing the previous value, it's just get reset every time. Maybe because I am using new FileWriter? I don't know how to do it.
If I use (fi, true), the score is storing like this - 04060100, that means the first line isn't going anywhere, all of the scores are writing in the first line only but I need to store the score in the first line only so that I can read the first line only, high score can't be multiple right?
What to do? I am new to this file storing system in Java.
Yes ... that is a much clearer explanation of what you are trying to do than what you wrote in your original question. (If only you have explained it properly in the first instant ...)
The solution is to NOT open the file for writing until you know that it needs to be written. The logic should be:
What your code currently does is to open for writing before you even read the file. That truncates the file, so that when you try to read the current high score the information has already been trashed.
Note that it is not the
BufferedWriterorBufferedReaderthat is the problem. The damage is done by calling theFileWriterconstructor. (The javadoc should explain it.)