我想为我的一个程序创建一个高分值方法,但它不能正常工作,因为我需要它。我所遇到的问题是如何告诉程序应该从哪一行读取它应该写入的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();
当我运行它,只写在文件的最后高分程序。我怎么能解决这个问题?
你正在以写模式打开文件,这将重新创建该文件,如果它存在。尝试以追加模式打开。 –