How to Write to a File in Java
So far, we were seeking outputs in the console area. But we can get it in a file as well. Yes, we are going to learn how to write to a file in Java hereby and by the time we are done, I am pretty sure you would only want to see your outputs in a file.
In projects all across the globe, it’s one of those preferred methods that clients expect. No, if you really think about it, why would someone want their output in your Eclipse IDE console? That’s just for you to see, or reckon. It is only reasonable to get your output slapped on a text file.
How to Write to a File in Java
Like the previous Reader Classes, there are many Writer Classes too that will help you get the job done. They are namely:
- BufferedWriter and FileWriter
- Abstract Writer Class
- Files and Paths
What if I say there is a Writer to a Reader? It seems only natural right? So like there were numerous ways to read a file in Java, there are also plenty of ways on how to write to a file in Java. We are going to learn all the methods that have been jotted above one by one. So brace yourself! Learning is coming.
BufferedWriter and FileWriter Class
You don’t look mighty surprised to learn about a class called BufferedWriter. Oh! Is it because you have heard about BufferedReader Class before? Good thing you remember that from the previous chapter.
Like there was readLine() method to read from a BufferedReader class, for BufferedWriter we have a method called write(String str).
Doesn’t that make life much simpler?
Step 1: Add the following code in the main method:
BufferedWriter bw = new BufferedWriter(new FileWriter(path));
Here while replacing ‘path’ with the exact folder location, you also need to specifically provide the name of the file you wish to create with the extension.
Make sure you put ‘\\’ to identify folders in Eclipse.
Step 2: Notice the red error sign on the bulb to the left? If you put the cursor over there you realize you need to throw an IOexception. Click on the sign and then press enter when the option comes. It will automatically add “throws IOException” to your main method. You can alternatively type that manually too.
Step 3: Time to use the “write(String str)” method to write something in the file that will be created by the name Penny.
All you have to do is type bw.write(“———Enter your data here———-“) in the next step. Just put your own data in the form of String by using the double quotes. I have typed in the following:
You can go ahead and close the called bw object with a bw.close(); code as well.
Step 4: Time to run the code. Click on the green arrow button. Here’s what you will get:
In a folder at the location specified by you in place of ‘path’ you will find a text file named Penny. Whatever you have typed in the write method will be reflected there as is.
Using FileOutputStream to write to a file in Java is equally easy. You can choose to display byte info or String info on a file depending upon your requirement.
Yes FileOutputStream Class is one of the most sought after ways to learn how to write to a file in Java.
When you Need to Display String
FileOutputStream Class has a write method that takes parameters as an array with return type as byte. So what we will do here is declare a String that needs to be printed beforehand, and then call the method getBytes() using it to slap it on the text file.
Step 1: Declare FileOutputStream Class and set the path mentioning the name of the file and the format you want your file in.
Step 2: Time to declare that String we had talked about. Sheldon is calling out peeps.
Step 3: When there is no way to call a String, simply retrieve all the bytes from it using getBytes. It will change all the data from a string in the format of bytes. To do that you gotta call getBytes(String) method and then assign it to an array:
The above step has taken info out of our String s in the form of bytes and assigned to the byte array. We still gotta print everything in our ‘Penny’ file.
Step 4: The last step in our code is to call the write method of FileOutputStream that only takes array for parameters.
You can choose to close it eventually as good habits dictate.
Step 5: Run the program. This is what you will get in your file:
When You Need to Write Byte
Alternatively, if you just want to write byte info in your text file, it is the easiest thing to do. Simply use the write(byte) method and you are done. Use the following:
You will get this output for the above code:
Yet another method for learning how to write to a file in Java is the one that makes use of PrintWriter. It’s one of the better ways I guess, because it doesn’t entail writing unwanted code. Just a mere declaration and then calling the method println() to display the result. That’s it!
Here are the steps to display the intended result on a text file:
Step 1: Create an object of the PrintWriter Class specifying the path and the name of your text file:
Step 2: We can make use of a simple println to print our String in a line. I know the familiarity might have brought a smile to your face.
Step 3: It is pretty important to close this PrintWriter object. Let’s mark it as our 3rd crucial step.
Step 4: Time to run this beauty. Click on the green arrow button and check the output:
Using Abstract Writer Class
Another one of those preferred ways in the Java universe, although I believe it should be learnt after you are well aware about Abstract Classes. It unnecessarily complicates things. Our brains can only take so much! Anyways just for the sake of learning yet another method we are gonna see what exactly we can achieve via Writer Class.
Writer class is exactly what its moniker suggests it is. Helps us in writing stuff.
We are going to make use of its method write() to print our desirable String.
Step 1: Abstract Classes cannot be instantiated, and so there’s no need to write “new Writer()” here for instantiation. We can directly assign it against OutputStreamWriter and FileOutputStream. The latter would let the Stream know about the path where we intend to get the output.
Step 2: Bring the cavalry in by using its write method and displaying the intended String in its parameter itself.
Step 3: Close it eventually. Somehow it doesn’t work when you don’t.
Step 4: Run the program and we will get the same result:
Then there is this FileWriter Class that is nothing but a walk in the park.
There is this write method herein that takes String as parameter. So there is literally nothing else that we need to do here.
Step 1: Instantiate FileWriter by specifying the name of the path, and the file name.
Step 2: Call the write(String) method and specify the String in its parameter. This part must be the easiest for you.
Step 3: Don’t forget to close this one. Use close() method.
Step 4: Run the green lantern.
Can learning how to write to a file in Java be more fun?
Files and Paths
This brings us to the modern way of dealing with inputs and outputs – Using the nio.file.Files class and nio.file.Paths.
Step 1: First job would be to of course import the Class location. I prefer to use “import nio.file.*;” to import all relevant files needed. Type that right after your package is declared.
Step 2: The second step would be to put whatever you wish to write in a String beforehand since we are going to use that String to call getBytes() method.
Step 3: Time to put the badass one line code to solve our problem. Type the following one liner in your existing code:
Files.write(Paths.get("C:\\Users\\Scott\\Desktop\\I am a writer\\DumbItDude\\Java\\code\\Penny.txt"), content.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
I know this might have confused you, but there are four parameters that Files.write demands, and I have simply provided those. You just pay attention to the
Here how it would appear in your IDE:
Step 4: Run this program by summoning the green devil:
With that concludes our painstaking search for learning how to write to a file in Java.