如何将文本附加到 Java 中的现有文件?

新手上路,请多包涵

我需要将文本重复附加到 Java 中的现有文件中。我怎么做?

原文由 flyingfromchina 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 598
2 个回答

你这样做是为了记录目的吗?如果是这样,那么有 几个库。其中最流行的两个是 Log4jLogback

Java 7+

对于一次性任务, Files 类 使这很容易:

 try {
    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

小心:如果文件不存在,上述方法将抛出 NoSuchFileException 。它也不会自动附加换行符(在附加到文本文件时通常需要)。另一种方法是同时传递 CREATEAPPEND 选项,如果文件不存在,它将首先创建文件:

 private void write(final String s) throws IOException {
    Files.writeString(
        Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
        s + System.lineSeparator(),
        CREATE, APPEND
    );
}

但是,如果您将多次写入同一个文件,则上述代码段必须多次打开和关闭磁盘上的文件,这是一个缓慢的操作。在这种情况下, BufferedWriter 更快:

 try(FileWriter fw = new FileWriter("myfile.txt", true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw))
{
    out.println("the text");
    //more code
    out.println("more text");
    //more code
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

笔记:

  • FileWriter 构造函数的第二个参数将告诉它附加到文件,而不是写入新文件。 (如果文件不存在,将被创建。)
  • 建议对昂贵的写入器使用 BufferedWriter (例如 FileWriter )。
  • 使用 PrintWriter 可以访问 println 语法,您可能习惯于 System.out
  • 但是 BufferedWriterPrintWriter 包装器并不是绝对必要的。

较早的 Java

 try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}


异常处理

如果您需要对旧 Java 进行强大的异常处理,它会变得非常冗长:

 FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
    fw = new FileWriter("myfile.txt", true);
    bw = new BufferedWriter(fw);
    out = new PrintWriter(bw);
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}
finally {
    try {
        if(out != null)
            out.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(bw != null)
            bw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(fw != null)
            fw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
}

原文由 Kip 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 fileWriter 并将标志设置为 true 进行附加。

 try
{
    String filename= "MyFile.txt";
    FileWriter fw = new FileWriter(filename,true); //the true will append the new data
    fw.write("add a line\n");//appends the string to the file
    fw.close();
}
catch(IOException ioe)
{
    System.err.println("IOException: " + ioe.getMessage());
}

原文由 northpole 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题