[英]how to append file in java
How do I append the highscore into highscore.txt file at the correct position in descending order? 如何将highscore按降序附加到highscore.txt文件中的正确位置? The method uses readHighScore(int score) method created previously to find the line number where the record should be inserted.
该方法使用之前创建的readHighScore(int score)方法来查找应在其中插入记录的行号。 This is what I got so far:
这是我到目前为止所得到的:
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.*/
}
It's very easy if you want to append data at the end, and almost impossible if you want append data at the middle. 如果要在末尾附加数据非常容易,而如果要在中间附加数据几乎是不可能的。 Much easy read all file in memory, change it and save all file again, overwriting old informaton.
轻松读取内存中的所有文件,进行更改并再次保存所有文件,覆盖旧的信息非常容易。
For example: 例如:
// 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.