In this post, you will lean how to write file in Java. 4 various ways will be used :

1- BufferedWriter

Since JDK 1.1

The first way to write file in Java is by using the BufferedWriter class from the java.io package. Below an example :

System.getProperty(“line.separator”) is used to separate lines in text files.

Note that the file will be overwritten each time you lunch your program. If you want to append your content into the existing file, use:

Instead of

2- PrintWriter

The second way to write file in Java is to use PrintWriter class from the java.io package. You can use it as following :

In the two earlier examples, if the writing string is null; the system will throw a java.lang.NullPointerException. If you want to print the string even if it is null so use

instead of

3- Try with resources

Since JDK 1.7

The try with resources statement ensures that each resource is closed at the end of the statement. No need to use finally block to ensure the closing of the resource.

4 – Apache Commons IO

Since JDK 1.6 For Commons IO 2.4

Since JDK 1.5 For Commons IO 2.2

You can also use the Apache Commons IO library to read file in Java. To do this, add the following dependency to you pom.xml

The Apache Commons IO library offers the FileUtils class to deal with files and can be very useful if all your content is on a Collection. In this case, use writeLines

If you want to append your content into the end of the file use :