Today we will look into how to append to a file in java. Java append to file is a common java IO operation. For example, whenever we print something to server logs, it gets appended to the existing file.

Java append to file

We can append to file in java using following classes.

  1. Java append to file using FileWriter
  2. Java append content to existing file using BufferedWriter
  3. Append text to file in java using PrintWriter
  4. Append to file in java using FileOutputStream
  5. java-append-to-file

If you are working on text data and the number of write operations is less, use FileWriter and use its constructor with append flag value as true. If the number of write operations is huge, you should use the BufferedWriter.

To append binary or raw stream data to an existing file, you should use FileOutputStream.

Java append to file using FileWriter

Here is the short program to append to file in java using FileWriter. We will look into a complete Java append to file example program later on.

Java append content to existing file using BufferedWriter

Append text to file in java using PrintWriter

We can also use PrintWriter to append to file in java.

Append to file in java using FileOutputStream

You should use FileOutputStream to append data to file when it’s raw data, binary data, images, videos etc.

Java append to file example

Here is the final java append to file program showing all the different options we discussed above.

That’s all for append to file in java program.

References:

By admin

Leave a Reply