How to append text to an existing file in Java

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


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

Java 7+

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
}

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
}

Notes:

  • 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.

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

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

    您可以使用fileWriter将标志设置为true来进行追加。

    try
    {
        String filename= "MyFile.txt";
        FileWriter fw = new FileWriter(filename,true); //the true will append the new data
        fw.write("add a linen");//appends the string to the file
        fw.close();
    }
    catch(IOException ioe)
    {
        System.err.println("IOException: " + ioe.getMessage());
    }
    

    Shouldn't all of the answers here with try/catch blocks have the .close() pieces contained in a finally block?

    Example for marked answer:

    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();
        }
    } 
    

    Also, as of Java 7, you can use a try-with-resources statement. No finally block is required for closing the declared resource(s) because it is handled automatically, and is also less verbose:

    try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
        out.println("the text");
    }catch (IOException e) {
        System.err.println(e);
    }
    
    链接地址: http://www.djcxy.com/p/44052.html

    上一篇: Spring框架到底是什么?

    下一篇: 如何将文本追加到Java中的现有文件