如何写入文本文件中的特定行?

时间:2015-10-05 19:52:39

标签: java

我试图为我的某个程序创建一个高分方法,但它不能按我的意愿工作。我遇到的问题是如何告诉程序它应该写入的txt文件(Highscore文件)中的哪一行。

我做了如下:

我创建了一个查找文件中行数的方法

  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;      

}

然后我尝试使用for循环,每当程序到达txt文件中的空白区域时,将分数打印到文本文件中:

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();

当我运行程序时,它只会写入文件中的最后一个高分。我怎么能解决这个问题?

2 个答案:

答案 0 :(得分:2)

每次写入该文件时,该文件的内容都会被覆盖。 为了保持整个书面内容,您需要将分数附加到文本文件中。

请参阅以下链接:

How to append text to an existing file in Java

答案 1 :(得分:1)

如果您的目标是附加到现有文件内容,请按以下步骤操作:

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

请注意new FileWriter("Highscores", true)中的boolean参数,该参数表示现有文件内容未被覆盖,但会被追加。

相关问题