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

问题:

我需要将文本重复附加到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
}

 Careful: The above approach will throw a NoSuchFileException if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Steve Chambers’s answer covers how you could do this with Files class.
但是,如果要多次写入同一个文件,上面的文件必须多次打开和关闭,这是一个很慢的操作。在这种情况下,缓冲写入器更好:

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

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: How to append text to an existing file in Java

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

− 6 = 4