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


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


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
}

但是,如果您要多次写入同一文件,则必须多次打开和关闭磁盘上的文件,这是一个很慢的操作。在这种情况下,缓冲编写器更好:

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构造函数的第二个参数将告诉它附加到文件,而不是写一个新文件。(如果该文件不存在,则会创建该文件。)
  • BufferedWriter对于昂贵的作家(例如FileWriter),建议使用a 。
  • 使用a PrintWriter可以访问println您可能习惯的语法System.out。
  • 但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
    }
}