【问题标题】:how to append file in java如何在java中追加文件
【发布时间】:2016-03-18 13:08:28
【问题描述】:

如何按降序将高分附加到 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.*/
        }

【问题讨论】:

  • 您要追加到文件末尾还是文件中间?
  • 我认为它应该是前 10 名,所以也许是文件的结尾?我不确定。
  • 如果您不需要文件顶部的旧信息,则将数据读取到内存中,更改内存中的信息并再次保存会容易得多。
  • 不要使用 FileWriter。它不允许您指定要使用的字符编码。这是 2015 年。使用 Paths.get() 和 Files.newBufferedWriter()。

标签: java file append


【解决方案1】:

如果你想在末尾追加数据,这很容易,如果你想在中间追加数据,那几乎是不可能的。很容易读取内存中的所有文件,更改它并再次保存所有文件,覆盖旧信息。

例如:

// 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

【讨论】:

  • 你是怎么做到的?
  • 我在帖子中添加示例
  • 谢谢,很有帮助
  • 如果这个答案对你来说足够了,你能接受这个答案吗?
猜你喜欢
  • 1970-01-01
  • 2011-08-19
  • 2018-07-07
  • 1970-01-01
  • 2011-08-02
  • 2016-11-14
  • 1970-01-01
  • 2016-04-27
  • 2013-09-14
相关资源
最近更新 更多