How to overwrite file via java nio writer?
Solution 1:
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
, andWRITE
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 of0
Solution 2:
You want to use both StandardOpenOption.TRUNCATE_EXISTING and StandardOpenOption.CREATE options together:
Files.write(path, content.getBytes(),
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING );