java - 如何在 Java 中向现有文件追加文本?

标签 java file-io io text-files

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

最佳答案

您这样做是为了记录目的吗?如果是的话有several libraries for this 。其中最受欢迎的两个是 Log4jLogback .

Java 7+

对于一次性任务,Files class让这变得容易:

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

关于java - 如何在 Java 中向现有文件追加文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58036834/

相关文章:

java - 如何通过 Servlet 的 doPost() 方法在 Tomcat 服务器上创建文件?

io - 使用 io.Copy 响应时,谁应该为错误负责?

java - 来自 adb install 的 INSTALL_PARSE_FAILED_NO_CERTIFICATES;使用Java 6、Android 5.0.2

java - 什么是反射,它为什么有用?

iphone - Objective-C 中是否有从字符串递归创建目录的方法?

c - 如何读入文本文件中的最后一个单词并读入 C 中的另一个文本文件?

java - 我的程序想要继续从命令行获取输入

java - Hibernate:如何在删除拥有的实体后更新父行

java - 什么是 Guava 的 SingletonImmutableBiMap

java - 如何在java中读取这些特定行