简体   繁体   中英

How to write to a specific line in a text file?

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM