Java IO Tutorial

How to append text to a file in Java

This article shows how to use the following Java APIs to append text to the end of a file.

  1. Files.write – Append a single line to a file, Java 7.
  2. Files.write – Append multiple lines to a file, Java 7, Java 8.
  3. Files.writeString – Java 11.
  4. FileWriter
  5. FileOutputStream
  6. FileUtils – Apache Commons IO.

In Java, for NIO APIs like Files.write, we can use StandardOpenOption.APPEND to enable the append mode. For examples:


	// append a string to the end of the file
	private static void appendToFile(Path path, String content)
		  throws IOException {

			Files.write(path,
							content.getBytes(StandardCharsets.UTF_8),
							StandardOpenOption.CREATE,
							StandardOpenOption.APPEND);

	}

For classic IO APIs like FileWriter or FileOutputStream, we can pass a true to the constructor’s second argument to enable the append mode. For examples:


	// append to the file
	try (FileWriter fw = new FileWriter(file, true);
       BufferedWriter bw = new BufferedWriter(fw)) {
      bw.write(content);
      bw.newLine();
  }

	// append to the file
	try (FileOutputStream fos = new FileOutputStream(file, true)) {
      fos.write(content.getBytes(StandardCharsets.UTF_8));
  }

1. Append a single line to a file – Files.write

If the file does not exist, the API throws NoSuchFileException


	Files.write(path, content.getBytes(StandardCharsets.UTF_8),
	                StandardOpenOption.APPEND);

The better solution always combines StandardOpenOption.CREATE and StandardOpenOption.APPEND. If the file does not exist, the API will create and write text to the file; if the file exists, append the text to the end of the file.


	Files.write(path, content.getBytes(StandardCharsets.UTF_8),
	                StandardOpenOption.CREATE,
	                StandardOpenOption.APPEND);

1.1 The below example shows how to append a single line to the end of a file.

FileAppend1.java

package com.mkyong.io.file;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FileAppend1 {

    private static final String NEW_LINE = System.lineSeparator();

    public static void main(String[] args) throws IOException {

        Path path = Paths.get("/home/mkyong/test/abc.txt");
        appendToFile(path, "hello world" + NEW_LINE);

    }

    // Java 7
    private static void appendToFile(Path path, String content)
				throws IOException {

        // if file not exists throws java.nio.file.NoSuchFileException
        /* Files.write(path, content.getBytes(StandardCharsets.UTF_8),
						StandardOpenOption.APPEND);*/

        // if file not exists, create and write to it
				// otherwise append to the end of the file
        Files.write(path, content.getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND);

    }

}

Output

Run 1st time.

/home/mkyong/test/abc.txt

hello world

Run 2nd time.

/home/mkyong/test/abc.txt

hello world
hello world

2. Append multiple lines to a file – Files.write

The Files.write also supports the Iterable interface for multiple lines, we can append a List into a file.


		// append lines of text
    private static void appendToFileJava8(Path path, List<String> list)
			throws IOException {

        // Java 7?
        /*Files.write(path, list, StandardCharsets.UTF_8,
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND);*/

        // Java 8, default utf_8
        Files.write(path, list,
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND);

    }

3. Java 11 – Files.writeString in append mode.

In Java 7, we need to convert a String into a byte[] and write or append it to a file.


	String content = "...";

	Files.write(path, content.getBytes(StandardCharsets.UTF_8),
					StandardOpenOption.CREATE,
					StandardOpenOption.APPEND);

In Java 11, we can use the new Files.writeString API to write or append a string directly into a file. The append mode works the same way.


	// Java 11, writeString, append mode
  private static void appendToFileJava11(Path path, String content)
			throws IOException {

      // utf_8
      /*Files.writeString(path, content, StandardCharsets.UTF_8,
              StandardOpenOption.CREATE,
              StandardOpenOption.APPEND);*/

      // default StandardCharsets.UTF_8
      Files.writeString(path, content,
              StandardOpenOption.CREATE,
              StandardOpenOption.APPEND);
  }

4. FileWriter

For the legacy IO APIs like FileWriter, the constructor’s second argument indicates the append mode.


	// append
	// if file not exists, create and write
	// if the file exists, append to the end of the file
	try (FileWriter fw = new FileWriter(file, true);
			 BufferedWriter bw = new BufferedWriter(fw)) {

			bw.write(content);
			bw.newLine();   // add new line, System.lineSeparator()

	}

4.1 The below example shows how to use FileWriter to append a single line to the end of a file.

FileAppend4.java

package com.mkyong.io.file;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileAppend4 {

	public static void main(String[] args) throws IOException {

			File file = new File("/home/mkyong/test/abc.txt");
			appendToFileFileWriter(file, "hello world");
			System.out.println("Done");

	}

	private static void appendToFileFileWriter(File file, String content)
			throws IOException {

			// default - create and write
			// if file not exists, create and write
			// if file exists, truncate and write
			/*try (FileWriter fw = new FileWriter(file);
					 BufferedWriter bw = new BufferedWriter(fw)) {
					bw.write(content);
					bw.newLine();
			}*/

			// append mode
			// if file not exists, create and write
			// if file exists, append to the end of the file
			try (FileWriter fw = new FileWriter(file, true);
					 BufferedWriter bw = new BufferedWriter(fw)) {

					bw.write(content);
					bw.newLine();   // add new line, System.lineSeparator()

			}

	}

}

4.2 The below example append a List or multiple lines to the end of a file.


	private static void appendToFileFileWriter(
			File file, List<String> content) throws IOException {

      try (FileWriter fw = new FileWriter(file, true);
           BufferedWriter bw = new BufferedWriter(fw)) {

          for (String s : content) {
              bw.write(s);
              bw.newLine();
          }
      }

  }

5. FileOutputStream

The append mode of FileOutputStream is working the same as FileWriter.


	private static void appendToFileFileOutputStream(File file, String content)
			throws IOException {

      // append mode
      try (FileOutputStream fos = new FileOutputStream(file, true)) {
          fos.write(content.getBytes(StandardCharsets.UTF_8));
      }

  }

6. FileUtils

The below example uses the popular Apache commons-io FileUtils.writeStringToFile to append a string to the end of a file.

pom.xml

	<dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.7</version>
  </dependency>

import org.apache.commons.io.FileUtils;

    private static void appendToFileFileUtils(File file, String content)
			  throws IOException {

				// append mode
        FileUtils.writeStringToFile(
                file, content, StandardCharsets.UTF_8, true);

    }

Review the FileUtils.writeStringToFile signature; the last or fourth argument indicates the append mode.


	public static void writeStringToFile(final File file, final String data,
				final Charset charset,final boolean append)
				throws IOException {

      try (OutputStream out = openOutputStream(file, append)) {
          IOUtils.write(data, out, charset);
      }

  }

7. In the old days.

Before Java 7, we can use the FileWriter to append text to a file and close the resources manually.

ClassicBufferedWriterExample.java

package com.mkyong;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class ClassicBufferedWriterExample {

    public static void main(String[] args) {

        BufferedWriter bw = null;
        FileWriter fw = null;

        try {

            String content = "Hello";

            fw = new FileWriter("app.log", true);
            bw = new BufferedWriter(fw);
            bw.write(content);

        } catch (IOException e) {
            System.err.format("IOException: %s%n", e);
        } finally {
            try {
                if (bw != null)
                    bw.close();

                if (fw != null)
                    fw.close();
            } catch (IOException ex) {
                System.err.format("IOException: %s%n", ex);
            }
        }
    }
}

P.S. The above code is just for fun and legacy purposes, always sticks with try-with-resources to close resources.

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
12 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
adfgadfga
6 years ago

you can append the text to new line each time, instead of end of the file, by adding:
bw = new BufferedWriter(fw); [original code]
bw.newLine(); [new code]
bw.write(data); [original code]

akungery
9 years ago

how if i want to write that String data on specific line?
e.g.
bufferWritter.writeLine(4);
bufferWritter.write(data);
bufferWritter.close();
how to do something like that?

dalwin
4 years ago

what about to append an existing word document? like two methods 1 is to create a word document plus text then the 2nd method is to append to that created word document..@mkyong

Ye ChaoHui
10 years ago

//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}

if not do this and file not exist, will create a file himself?

Kraeuterbutter8
9 years ago
Reply to  Ye ChaoHui

No, i’ve tested it, and as it seems, it won’t create it until you call “file.createNewFile();”

Zenith
10 years ago

Gr8!! That worked!! Thank you 🙂

Dave
11 years ago

Hi, Thanks for the code snippet, it’s useful. It’s probably a good idea to wrap the bufferWritter.close(); in a finally block in case of any exceptions before then. This will prevent unclosed filehandles on the FS.

A.J
11 years ago

Hi

thanks for this code it truly saved me a lot of time and headache tablets loll

Kind Regards
A.J Bosch

Divyasree
11 years ago

haii friends,
Here why we have to pass the FileWriter variable to the BufferedWriter as argument??