How to overwrite file via java nio writer?

JavaIoNioJava Io

Java Problem Overview


I try files writer as follows:

String content = "Test File Content";
  • I used as like : Files.write(path, content.getBytes(), StandardOpenOption.CREATE);

If file is not create, file is created and content is written. But If file available , the file content is Test File ContentTest File Content and if the code is run repeat, the file content is Test File ContentTest File ContentTest File Content ...

  • I used as like : Files.write(path, content.getBytes(), StandardOpenOption.CREATE_NEW); ,

If file is not create, file is created and than thow an exception as follow:

> java.nio.file.FileAlreadyExistsException: > /home/gyhot/Projects/indexing/ivt_new/target/test-classes/test_file > at > sun.nio.fs.UnixException.translateToIOException(UnixException.java:88) > at > ...

How to overwrite file via java new I/O?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncguzelView Question on Stackoverflow
Solution 1 - JavaRamonBozaView Answer on Stackoverflow
Solution 2 - JavarolflView Answer on Stackoverflow