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.
1 2 3 4 5 6 7 8 |
public static void main(String[] args) throws IOException { File myFile = new File("filename.txt"); PrintWriter myWriter = new PrintWriter("filename.txt"); myWriter.println("This is first line in my lovely file"); myWriter.close(); } |
At the beginning we should create the file:
1 2 3 |
File myFile = new File("filename.txt"); |
When we have our file created, we can now write to it using PrintWriter class.
1 2 3 |
PrintWriter myWriter = new PrintWriter("filename.txt"); |
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.
1 2 3 |
public static void main(String[] args) throws IOException |
Now, using our freshly made writer we can easily add new lines of text to our file:
1 2 3 |
myWriter.println("This is first line in my lovely file"); |
When we decide that we won’t be using our file more we need to remember about closing the PrintWriter.
1 2 3 |
myWriter.close(); |
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()
.
1 2 3 4 5 |
List<String> linesOfTxt = Arrays.asList("First line is here", "Second line is lower"); Path myFile2 = Paths.get("filename2.txt"); Files.write(myFile2, linesOfTxt); |
Firstly, we will create all lines of our text using List.
1 2 3 |
List<String> linesOfTxt = Arrays.asList("First line is here", "Second line is lower"); |
Then, we should specify the name of the file using Path class
1 2 3 |
Path myFile2 = Paths.get("filename2.txt"); |
and after all, we can create a full file using the previous objects:
1 2 3 |
Files.write(myFile2, linesOfTxt); |
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.