协慌网

登录 贡献 社区

如何在 Java 中将文本追加到现有文件?

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

答案

您是否出于记录目的这样做?如果是这样的话,有几个库。最受欢迎的两个是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构造函数的第二个参数将告诉它追加到文件中,而不是写入新文件。 (如果文件不存在,则将创建它。)
  • 对于昂贵的写入器(例如FileWriter ),建议使用BufferedWriter
  • 使用PrintWriter可让您访问System.out可能习惯的println语法。
  • 但是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
    }
}

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

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());
}

在 try / catch 块中,不是所有答案都在 finally 块中包含. close()块吗?

标记答案的示例:

PrintWriter out = null;
try {
    out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)));
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
} finally {
    if (out != null) {
        out.close();
    }
}

另外,从 Java 7 开始,您可以使用try-with-resources 语句。不需要 finally 块来关闭已声明的资源,因为它是自动处理的,并且也不太冗长:

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
}