How to append text to an existing file in Java

java program to append text to an existing file
java append to beginning of file
java append to file = new line
java 8 append to file
java append to file create if not exists
java filewriter append
java write to file
java fileoutputstream append new line

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

How to append text to an existing file in Java, Learn to append content to file in java using BufferedWritter , PrintWriter To append content to an existing file, open file writer in append mode by passing second argument as true . Use PrintWriter to write formatted text to a file. This class  the true allows to append the data in the existing file. If we will write. FileOutputStream fos = new FileOutputStream("File_Name"); It will overwrite the existing file. So go for first approach.

You can use fileWriter with a flag set to true , for appending.

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

Java - Append to File, The Java.io.BufferedWriter class writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single  Java Program to Append Text to an Existing File Object Oriented Programming Java8 Java Programming The Java.io.BufferedWriter class writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

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

Java append to file, In Java we can append a string in an existing file using FileWriter which has an option to open file in append mode. Let us create a sample file with some text. You can append text into an existing file in Java by opening a file using FileWriter class in append mode. You can do this by using special constructor provided by FileWriter class, which accepts a file and a boolean, which if passed as true then open the file in append mode. This means you can write new content at the end of the file.

Edit - as of Apache Commons 2.1, the correct way to do it is:

FileUtils.writeStringToFile(file, "String to append", true);

I adapted @Kip's solution to include properly closing the file on finally:

public static void appendToFile(String targetFile, String s) throws IOException {
    appendToFile(new File(targetFile), s);
}

public static void appendToFile(File targetFile, String s) throws IOException {
    PrintWriter out = null;
    try {
        out = new PrintWriter(new BufferedWriter(new FileWriter(targetFile, true)));
        out.println(s);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

Java Program to Append Text to an Existing File, This is a Test file. Example 1: Append text to existing file. import java.io.​IOException; import java.nio.file  How to append text to an existing file in Java. Ask Question It also does not append a newline automatically (which you often want when appending to a text file).

To slightly expand on Kip's answer, here is a simple Java 7+ method to append a new line to a file, creating it if it doesn't already exist:

try {
    final Path path = Paths.get("path/to/filename.txt");
    Files.write(path, Arrays.asList("New line to append"), StandardCharsets.UTF_8,
        Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (final IOException ioe) {
    // Add your own exception handling...
}

Note: The above uses the Files.write overload that writes lines of text to a file (i.e. similar to a println command). To just write text to the end (i.e. similar to a print command), an alternative Files.write overload can be used, passing in a byte array (e.g. "mytext".getBytes(StandardCharsets.UTF_8)).

Java, Java Input-Output: Exercise-16 with Solution. Write a Java program to append text to an existing file. Sample Solution: Java Code: 1 Java append to file. 1.1 Java append to file using FileWriter; 1.2 Java append content to existing file using BufferedWriter; 1.3 Append text to file in java using PrintWriter; 1.4 Append to file in java using FileOutputStream; 1.5 Java append to file example

Java Program to Append Text to an Existing File, 2. Using FileWriter. Here's a simple test – reading an existing file, appending some text, and then making sure that got appended correctly: ? How to append a string in an existing file ? This example shows how to append a string in an existing file using filewriter method. The above code sample will produce the following result. The following is an example of append a string in an existing file in java. The above code sample will produce the following result.

Java exercises: Append text to an existing file, Files.write. Append a List into an existing file. FileExample.java. package com.​mkyong;  Java append/add content to an existing file. If you want your code to create a new file and erase previous existing file, FileWriter can simply take it place. To replace all content in an existing file, use this: FileWriter fstream = new FileWriter(loc); The code above will delete the existing file if it's name is use in new file being writting.

Java – Append Data to a File, Java | Appending String to a File. In Java we can append a string in an existing file using FileWriter which has an option to open file in append mode. Java FileWriter class is used to write character-oriented data to a file. It is character-oriented class which is used for file handling in Java.

Comments
  • You should either use java7 try-with-resources or put the close() in a finally block, in order to make sure that the file is closed in case of exception
  • updated with Java 7 syntax. exception handling is still left as an exercise for reader, but made the comment clearer.
  • Lets imagine that new BufferedWriter(...) throws an exception; Will the FileWriter be closed ? I guess that it will not be closed, because the close() method (in normal conditions) will be invoked on the out object, which int this case will not be initialized - so actually the close() method will not be invoked -> the file will be opened, but will not be closed. So IMHO the try statement should look like this try(FileWriter fw = new FileWriter("myFile.txt")){ Print writer = new ....//code goes here } And he should flush() the writer before exiting the try block!!!
  • Caution, the "Older java" example will not properly close the stream if an exception is thrown inside the try block.
  • A couple of possible "gotchas" with the Java 7 method: (1) If the file doesn't already exist, StandardOpenOption.APPEND won't create it - kind of like a silent failure as it won't throw an exception either. (2) Using .getBytes() will mean there is no return character before or after the appended text. Have added an alternative answer to address these.
  • close should be placed in finally block just like shown in @etech's answer in case exception would be thrown between creation of FileWriter and invoking close.
  • Good answer, although its better to use System.getProperty( "line.separator" ) for a new line rather than "\n".
  • @Decoded I've rolled back your edit on this answer, as it does not compile.
  • @Kip, What was the issue? I must have entered a "typo".
  • How bout try-with-resources? try(FileWriter fw = new FileWriter(filename,true)){ // Whatever }catch(IOException ex){ ex.printStackTrace(); }
  • When out goes out of scope, it is automatically closed when it gets garbage-collected, right? In your example with the finally block, I think you actually need another nested try/catch around out.close() if I remember correctly. The Java 7 solution is pretty slick! (I haven't been doing any Java dev since Java 6, so I was unfamiliar with that change.)