Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite file via java nio writer?

Tags:

java

io

java-io

nio

People also ask

How do I override an existing file in Java?

If a file already exists with that name, it will just return false: File f = new File("myfile. txt"); if (f. createNewFile()) { // If there wasn't a file there beforehand, there is one now. }

How do I overwrite an existing file?

Here it is: Navigate to source file in source directory, copy (Ctrl-C), navigate to destination file in destination directory, delete destination file (Del, Enter), paste (Ctrl-V), rename (F2) and edit name to destination name.

Does FileWriter overwrite existing file Java?

When you create a Java FileWriter you can decide if you want to overwrite any existing file with the same name, or if you want to append to any existing file.

What is Nio file in Java?

Java For Testers Java NIO package provide one more utility API named as Files which is basically used for manipulating files and directories using its static methods which mostly works on Path object.


You want to call the method without any OpenOption arguments.

Files.write(path, content.getBytes());

From the Javadoc:

The options parameter specifies how the the file is created or opened. 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


You want to use both StandardOpenOption.TRUNCATE_EXISTING and StandardOpenOption.CREATE options together:

Files.write(path, content.getBytes(),
         StandardOpenOption.CREATE,
         StandardOpenOption.TRUNCATE_EXISTING );