如何将highscore以高位顺序附加到正确位置的highscore.txt文件中?该方法使用先前创建的readHighScore(int score)方法来查找应插入记录的行号。这是我到目前为止所得到的:
public static void recordHighScore(String name, int score){
File file = new File("Test/highscore.txt");
FileWriter fwriter = new FileWriter(file, true);
try{
String userName = name+","+score;
fwriter.add(readHighScore(score), userName);
}catch(IOException io){
System.out.println("Missing File!");
}
/*Writes the high score into highscore.txt file, at the correct position (in descending order). This
method uses readHighScore( ) method to find the line number where the record should be
inserted.*/
}
答案 0 :(得分:0)
如果你想在最后附加数据,这很容易,如果你想在中间附加数据,几乎是不可能的。很容易读取内存中的所有文件,更改它并再次保存所有文件,覆盖旧的信息。
例如:
// read file to arraylist
Scanner s = new Scanner(new File("filepath"));
List<Score> list = new ArrayList<Score>();
while (s.hasNext()){
String[] a = s.next().split(",");
list.add(new Score(a[0], a[1]); ); // Score is class with name and score fields
}
s.close();
// working with List<Score>
// add new score to List<Score>
// save List<Score> to file like in your code