Languages
[Edit]
EN

Java - append text to existing file

0 points
Created by:
Brian-Tompset
491

In this article, we would like to show you how to append text to an existing file in Java.

Below examples present how to append text into the file using the following solutions:

  • Files.write (append single line - Java 7, multiple lines - Java 8),
  • Files.writeString (Java 11),
  • FileWriter,
  • FileOutputStream.

 

1. Files.write

Edit

In the below examples, we use Files.write to append some text at the end of the existing example.txt file.

1.1 Append single line

Edit

The result after three executions:

Java - append text to an existing file using Files.write - result
Java - append text to an existing file using Files.write - result

1.2 Append multiple lines

Edit

The result after one execution:

Java - append text to an existing file using Files.write - result
Java - append text to an existing file using Files.write - result

2. Files.writeString

Edit

In the below examples, we use Files.writeString to append some text at the end of the existing example.txt file.

Note:

In Java 7 with Files.write() method, we need to convert a String into a byte[] and then write or append it to a file.

With Java 11 File.writeString() method we can directly write or append the string into the file. 

Practical example: 

Result:

Java - append text to an existing file using Files.writeString - result
Java - append text to an existing file using Files.writeString - result

3. FileWriter

Edit

In the below examples, we use FileWriter to append some text at the end of the existing example.txt file.

The result after one execution:

Java - append text to an existing file using FileWriter - result
Java - append text to an existing file using FileWriter - result

4. FileOutputStream

Edit

In the below examples, we use FileWriter to append some text at the end of the existing example.txt file.

Result:

Java - append text to an existing file using FileOutputStream - result
Java - append text to an existing file using FileOutputStream - result

Note:

Append mode of FileOutputStream works the same as FileWriter.

Alternative titles

  1. Java - append data to existing file
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - file operations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join