如何在Java中将文本追加到现有文件? [英] How to append text to an existing file in Java?

查看:107
本文介绍了如何在Java中将文本追加到现有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将文本重复添加到Java中的现有文件中.我该怎么办?

I need to append text repeatedly to an existing file in Java. How do I do that?

推荐答案

您是否出于记录目的而这样做?如果是这样,则有为此的几个库.最受欢迎的两个是 Log4j

Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.

如果您只需要执行一次,则

If you just need to do this one time, the Files class makes this easy:

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.它还不会自动追加换行符(追加到文本文件时通常需要换行符). 史蒂夫·钱伯斯的答案介绍了如何使用Files类来实现此目的.

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.

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

However, if you will be writing to the same file many times, the above has to open and close the file on the disk many times, which is a slow operation. In this case, a buffered writer is better:

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包装器并不是严格必需的.
  • The second parameter to the FileWriter constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.)
  • Using a BufferedWriter is recommended for an expensive writer (such as FileWriter).
  • Using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
  • But the BufferedWriter and PrintWriter wrappers are not strictly necessary.
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进行健壮的异常处理,它将变得非常冗长:


Exception Handling

If you need robust exception handling for older Java, it gets very verbose:

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中将文本追加到现有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆