问题

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


#1 热门回答(657 赞)

你这样做是为了记录目的吗?如果有的话,有 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。它也不会自动追加换行符(当你追加到文本文件时经常需要它).Steve Chambers's answer使用Files类来解决这个问题。
但是,如果你要多次写入同一文件,则必须多次打开和关闭磁盘上的文件,这是一个很慢的操作。在这种情况下,缓冲编写器更好:

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语法。
  • 但BufferedWriter和PrintWriter包装并不是绝对必要的。

##旧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 热门回答(149 赞)

你可以使用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());
}

#3 热门回答(64 赞)

不应该在这里使用 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 statement。关闭声明的资源不需要finally块,因为它是自动处理的,并且也不那么详细:

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

原文链接