How to create and write to a file in Java

January 29, 2017

In this short tutorial, we will discuss how to create and write to a file in Java.

1. Creating file with PrintWriter

We will be using java.io.* package. We will create a file. And by using PrintWriter object we will write to it.

At the beginning we should create the file:

When we have our file created, we can now write to it using PrintWriter class.

It is worth to say, that in this constructor we don’t use our object but the file name directly. On that point, we should add an exception to our main method in case file doesn’t exist.

Now, using our freshly made writer we can easily add new lines of text to our file:

When we decide that we won’t be using our file more we need to remember about closing the PrintWriter.

2. Creating file using Files and Path classes

Another way to create and write to a file is Files class included in java.nio.file.* package. It is a little bit less intuitive but still worth to know. It was introduced in Java 7+. The methods used here are: asList(), get(), and write().

Firstly, we will create all lines of our text using List.

Then, we should specify the name of the file using Path class

and after all, we can create a full file using the previous objects:

And that’s it! It’s different but quicker because we don’t need to write line by line. In this method, we write text at once.

Click here to add a comment

Leave a comment: