How to write to a file in Java

In this post we will learn how to write to a file in Java using the following classes Files, BufferedWriter and FileOutputStream.

How to write to a File in Java using the Files class:

Below is an example of how to write to a file using the Files class. This will create a new file if one does not exist otherwise it will overwrite the existing file.

To append to an existing file you can do the following.

Output

File contents contains

How to write to a file in Java using the BufferedReader class:

Below is an example on how to write to a file using a BufferedReader. This will create a new file if one does not exist otherwise it will overwrite the existing file.

To append to an existing file you can pass a boolean to the FileWriter to notify it to append to the file.

Output

How to write to a file in Java using the FileOutputStream class:

In the final example we will demonstrate how to write to a file using FileOutputStream, this will create a new file if one does not exist or it will also overwrite the existing file if it does exist.

You can append to an existing file by passing a boolean when creating the FileOutputStream

Output

In conclusion we have demonstrated how to write to a new file, append to an existing file and overwrite an existing file. Below I have provided some links to the Java documentation for more information.

Similar posts:

  1. How to read a file in Java
  2. How to create a file in Java
  3. How to convert an InputStream to String in Java

References:

  1. Java Files API documentation
  2. Java BufferedWriter API documentation
  3. Java FileOutputStream API documentation

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *