javafilenullbufferedreaderbufferedwriter

How to stop BufferedWriter to assigning null value every time the method has been called?


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.


Solution

  • Okay I will try to make you understand. Look, I want to store the highscore only to that file. So at first when the program runs, the score will be 0 right? So the score.txt file will have 0 in the first line. Okay? After playing a game let's say I get a score of 50, so obviously 50 is greater than 0, then the score.txt file will have the 50 in the first line not 0. Now again I played the game and get a score of 30, which is not greater than 50 so the txt file will be the same, it contains the high score in the first line which is 50. When I scored 100 the txt will store the 100. Get it?

    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:

    1. Open file to read
    2. Read line containing high score
    3. Close
    4. If current score greater than high score
      1. Open file to write
      2. Write new high score
      3. Close.

    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 BufferedWriter or BufferedReader that is the problem. The damage is done by calling the FileWriter constructor. (The javadoc should explain it.)