Need to take some text and dump it in a file? There's an easy way to do that with Java NIO.
And in this guide, I'll show you how to make it happen.
I figured I'd write this article since I already covered how to read a text file line by line with NIO. Might as well cover both sides of that coin.
So let's get started.
The method I'll show you here will overwrite an existing file of the same name. In many cases, that's just fine.
But if you need to append text rather than overwrite the existing file, take a look at my guide on that subject.
If you want to know how to avoid overwriting an existing file, I have a guide for that as well.
The Code Is Why You're Here
You're probably here for some code and not a whole lot of warnings or intro text so... this:
final String path = "./contents.txt"; final String contents = "Good news"; Files.writeString(Paths.get(path), contents);
The first line is a path to the file. It's represented as a String object. In this case, it's going to write the output to a file called contents.txt in the root of the IDE project.
The second line specifies the String object that the code will write to the file. It's a simple string: "Good news".
The third and final line actually writes the String object to the text file.
But before it can do that, it must first convert the string path to a Java NIO Path object. It does that with the aid of the Paths.get() static method.
That Path object is the first parameter in the Files.writeString() method (also static). The second parameter is the String object that this little application will write to the file.
Note that you could also add OpenOption parameters as well. Since the code above doesn't use any OpenOption parameters, the file (if it exists) will get overwritten.
So once again: be careful about using FIles.writeString() this way unless you really know what you're doing.
The New Way: Better Than the Old Way
What I've just showed you is my preferred way of writing strings to disk. The Old School method involved the use of try-with-resources and an output stream.
It usually took a few more lines of code than what you saw above.
So I'd stick with this method and ditch the old way of doing things. You'll end up with tighter, cleaner code.
Wrapping It Up
Now you know how to write a string to a file using Java NIO.
Feel free to take what you've learned here and use it in your own applications.
Photo by from