[英]How to write to a specific line in a text file?
我正在嘗試為我的一個程序創建一個高分方法,但它不能按我的意願工作。 我遇到的問題是如何告訴程序它應該寫入的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();
當我運行程序時,它只會寫入文件中的最后一個高分。 我怎么能解決這個問題?
如果您的目標是附加到現有文件內容,請按以下步驟操作:
PrintWriter utström1 = new PrintWriter
(new BufferedWriter
(new FileWriter("Highscores", true)));
請注意new FileWriter("Highscores", true)
的boolean參數new FileWriter("Highscores", true)
,表示現有文件內容未被覆蓋,但會被追加。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.