1

I'm trying to create a highscore method for one of my programs but it is not working as I want it to. The problem im having is how to tell the program from which line in a txt file (Highscore file) it is supposed to write to.

I have done as follows:

I created a method that finds the number of lines in a file

  public static int countline (String filnamn)throws IOException {
  BufferedReader inström1 = new BufferedReader
                           (new FileReader(filnamn));
  int lines = 0;                           

     while(inström1.readLine() != null) {
        ++lines;       
     }
     inström1.close();

     return lines;      

}

Then i tried, using a for loop, to print a score to a text file everytime the program hits an empty space in the txt file:

PrintWriter utström1 = new PrintWriter
                        (new BufferedWriter
                        (new FileWriter("Highscores")));

for(int i = 0; i < countline("Highscores")+1; i++) {                                                                                          

   if(inström1.readLine() == null) {
   utström1.println(namn + ", " + (double)100*rätt/(rätt+fel) + "% rätt" + "\n");                                      
   }
}
utström1.close();

When I run the program it only writes over the last highscore in the file. How could I fix this?

Unknown
  • 59
  • 1
  • 7

2 Answers2

2

Each time when you write into that file,the content of that file gets overriden. In order to maintain the whole writen content you need to append the score to the text file.

See the following link:

How to append text to an existing file in Java

Community
  • 1
  • 1
1

If your objective is to append to the existing file content, here is how it can be done:

    PrintWriter utström1 = new PrintWriter
                    (new BufferedWriter
                    (new FileWriter("Highscores", true)));

Notice the boolean argument in new FileWriter("Highscores", true) which indicates the existing file content is not overwritten, but will be appended.

deepak marathe
  • 409
  • 3
  • 10