How to overwrite file via java nio writer? How to overwrite file via java nio writer? java java

How to overwrite file via java nio writer?


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 );