【问题标题】:Best strategy to add lines of text to a text file将文本行添加到文本文件的最佳策略
【发布时间】:2014-10-26 16:09:05
【问题描述】:

我正在使用 txt 文件,使用类 PrintWriter 创建它们。这允许我使用println(...) 方法在 txt 文件中打印一些内容。

但现在我需要在我创建的列表末尾添加一些内容。像这样:

PrintWriter writer = new PrintWriter("File.txt", "UTF-8");

writer.println("Hello");
writer.println("Josh!");

writer.close();

结果是这样的文件:

你好

乔希!

但是如果我想在文本底部添加新单词怎么办?我希望在内容更新的情况下覆盖文件“File.txt”?

你好

乔希!

你好吗?

我在想类似“好的,我必须在末尾添加另一行,因此读取所有文件,然后编写另一个文件(具有相同的名称和内容),在末尾添加一个新行”,但是这似乎太奇怪了,我觉得还有另一种简单的方法可以做到。还有什么想法吗?

【问题讨论】:

标签: java file io bufferedreader


【解决方案1】:

您可以简单地使用 FileWriter,它有一个可以启用的附加模式:

    FileWriter writer = new FileWriter("File.txt");

    writer.write("Hello\n");

    writer.write("Josh!\n");

    writer.close();

    writer = new FileWriter("File.txt", true);

    writer.append("Great!");

    writer.close();

【讨论】:

    【解决方案2】:

    你的怀疑是正确的。

    你应该使用try with resources(Java 7+):

    try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("File.txt", true)))) {
        out.println("How are you?");
    }catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    

    FileWriter constructor 的第二个参数将告诉它附加到文件(而不是清除文件)。对于昂贵的写入器(即 FileWriter),建议使用 BufferedWriter,并且使用 PrintWriter 可以让您访问您可能习惯于 System.out 的 println 语法。但是 BufferedWriter 和 PrintWriter 包装器并不是绝对必要的。

    这还允许您在每次运行时附加到文件,而不是替换整个文件。最后,尝试资源意味着您不必致电.close(),它已经为您完成了! Grabbed from here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-01
      • 2014-11-15
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多