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

2022-08-31 04:06:48

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


答案 1

您这样做是为了记录目的吗?如果是这样,有几个库可以做到这一点。其中最受欢迎的两个是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
}

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

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

但是,如果要多次写入同一文件,则上述代码段必须多次打开和关闭磁盘上的文件,这是一个缓慢的操作。在这种情况下,a 更快: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
  • 建议对昂贵的编写器使用 a(例如 )。BufferedWriterFileWriter
  • 通过使用 ,您可以访问您可能习惯于从 中学习的语法。PrintWriterprintlnSystem.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
    }
}

答案 2

可以将标志设置为 用于追加。fileWritertrue

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