printwriter using aHow to append text to an existing file in Java

15 Answers

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

    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
catch(IOException ioe)
    System.err.println("IOException: " + ioe.getMessage());
java append to file if exists

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

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)));
    } finally {
        if (out != null) {

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

Sample, using Guava:

File to = new File("C:/test/test.csv");

for (int i = 0; i < 42; i++) {
    CharSequence from = "some string" + i + "\n";
    Files.append(from, to, Charsets.UTF_8);

java 7+

In my humble opinion since I am fan of plain java, I would suggest something that it is a combination of the aforementioned answers. Maybe I am late for the party. Here is the code:

 String sampleText = "test" +  System.getProperty("line.separator");
 Files.write(Paths.get(filePath), sampleText.getBytes(StandardCharsets.UTF_8), 
 StandardOpenOption.CREATE, StandardOpenOption.APPEND);

If the file doesn't exist, it creates it and if already exists it appends the sampleText to the existing file. Using this, saves you from adding unnecessary libs to your classpath.

Using java.nio.Files along with java.nio.file.StandardOpenOption

    PrintWriter out = null;
    BufferedWriter bufWriter;

        bufWriter =
        out = new PrintWriter(bufWriter, true);
    }catch(IOException e){
        //Oh, no! Failed to create PrintWriter

    //After successful creation of PrintWriter
    out.println("Text to be appended");

    //After done writing, remember to close!

This creates a BufferedWriter using Files, which accepts StandardOpenOption parameters, and an auto-flushing PrintWriter from the resultant BufferedWriter. PrintWriter's println() method, can then be called to write to the file.

The StandardOpenOption parameters used in this code: opens the file for writing, only appends to the file, and creates the file if it does not exist.

Paths.get("path here") can be replaced with new File("path here").toPath(). And Charset.forName("charset name") can be modified to accommodate the desired Charset.

    String str;
    String path = "C:/Users/...the path..../iin.txt"; // you can input also..i created this way :P

    BufferedReader br = new BufferedReader(new InputStreamReader(;
    PrintWriter pw = new PrintWriter(new FileWriter(path, true));

            System.out.println("Enter the text : ");
            str = br.readLine();
    catch (Exception e) 
        //oh noes!

this will do what you intend for..

If we are using Java 7 and above and also know the content to be added (appended) to the file we can make use of newBufferedWriter method in NIO package.

public static void main(String[] args) {
    Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
    String text = "\n Welcome to Java 8";

    //Writing to the file temp.txt
    try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
    } catch (IOException e) {

There are few points to note:

  1. It is always a good habit to specify charset encoding and for that we have constant in class StandardCharsets.
  2. The code uses try-with-resource statement in which resources are automatically closed after the try.

Though OP has not asked but just in case we want to search for lines having some specific keyword e.g. confidential we can make use of stream APIs in Java:

//Reading from the file the first line which contains word "confidential"
try {
    Stream<String> lines = Files.lines(FILE_PATH);
    Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
} catch (IOException e) {

Create a function anywhere in your project and simply call that function where ever you need it.

Guys you got to remember that you guys are calling active threads that you are not calling asynchronously and since it would likely be a good 5 to 10 pages to get it done right. Why not spend more time on your project and forget about writing anything already written. Properly

    //Adding a static modifier would make this accessible anywhere in your app

    public Logger getLogger()
       return java.util.logging.Logger.getLogger("MyLogFileName");
    //call the method anywhere and append what you want to log 
    //Logger class will take care of putting timestamps for you
    //plus the are ansychronously done so more of the 
    //processing power will go into your application

    //from inside a function body in the same class ...{...

    getLogger().log(Level.INFO,"the text you want to append");

    /*********log file resides in server root log files********/

three lines of code two really since the third actually appends text. :P

You can also try this :

JFileChooser c= new JFileChooser();
File write_file = c.getSelectedFile();
String Content = "Writing into file"; //what u would like to append to the file

    RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
    long length = raf.length();
    raf.setLength(length + 1); //+ (integer value) for spacing;
catch (Exception e) {
    //any exception handling method of ur choice

FileOutputStream fos = new FileOutputStream("File_Name", true);

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.

I might suggest the apache commons project. This project already provides a framework for doing what you need (i.e. flexible filtering of collections).

My answer:

JFileChooser chooser= new JFileChooser();
File file = chooser.getSelectedFile();
String Content = "What you want to append to file";

    RandomAccessFile random = new RandomAccessFile(file, "rw");
    long length = random.length();
    random.setLength(length + 1);;
catch (Exception exception) {
    //exception handling

 * it will write content to a specified  file
 * @param keyString
 * @throws IOException
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
    // For output to file
    File a = new File(textFilePAth);

    if (!a.exists()) {
    FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
    BufferedWriter bw = new BufferedWriter(fw);
}// end of writeToFile()

1.7 Approach:

void appendToFile(String filePath, String content) throws IOException{

    Path path = Paths.get(filePath);

    try (BufferedWriter writer = 
                    StandardOpenOption.APPEND)) {

    try (BufferedWriter bWriter = 
                    StandardOpenOption.WRITE, StandardOpenOption.APPEND);
            PrintWriter pWriter = new PrintWriter(bWriter)
            ) {
        pWriter.println();//to have println() style instead of newLine();   
        pWriter.append(content);//Also, bWriter.append(content);