2015-10-05 169 views
1

我想爲我的一個程序創建一個高分值方法,但它不能正常工作,因爲我需要它。我所遇到的問題是如何告訴程序應該從哪一行讀取它應該寫入的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(); 

當我運行它,只寫在文件的最後高分程序。我怎麼能解決這個問題?

+0

你正在以寫模式打開文件,這將重新創建該文件,如果它存在。嘗試以追加模式打開。 –

回答

1

如果你的目標是要附加到現有文件內容,在這裏是如何可以做到:

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

通知boolean變量中new FileWriter("Highscores", true)表示現有文件內容未被覆蓋,但會被追加。