Do you have a requirement that calls for always overwriting an existing file? No problem, I'll show you how to do it with Java NIO.

The important thing here isn't what you do. It's what you don't do.

I'll explain what I mean.

Jammin' With the Javadoc

If you're a Java NIO aficionado, you probably want to use Files.write() to write your file.

So you head over to the Javadoc and take a look at the documentation for that method. You note that it has three parameters:

  • the Path
  • the byte array
  • OpenOption options

You may have noticed also that OpenOption is followed by an ellipsis. That means you can include as many OpenOption objects as you want.

What you may not know is that the ellipsis doesn't mean 1-to-many. It means 0-to-many.

You don't have to include any OpenOption objects at all!

And that's precisely what you'll do if you want to overwrite the file.

A Simple Test

Let's keep me honest with a simple test. Try something like this:

final String path = "./contents.txt";
final byte[] contents = "My stuff".getBytes();
Files.write(Paths.get(path), contents);

Go ahead and run that and you'll find that it creates a new file called contents.txt in the root of your IDE project or source tree. View that file with a text editor and you'll see the words "My stuff" in there with nothing else.

Run it again and take another look at the file. It got overwritten.

Instead of appending a new "My stuff" sequence of characters, it just overwrote the whole file.

That happens because the third line in the code block above doesn't include any OpenOption objects.

Here's what the docs have to say about that: "If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0."

So you can always overwrite files while keeping your code concise at the same time. Just don't add any OpenOption parameters to Files.write().

Wrapping It Up

Now you know how to always overwrite files with Java NIO.

Feel free to borrow the code above and update it to suit your own requirements.

Have fun!

Photo by Lisa from Pexels