Best way to write String to file using java nio

UPDATED:

Since Java11 there is a specific method to write strings using java.nio.file.Files:

Files.writeString(Paths.get(file.toURI()), "My string to save");

We can also customize the writing with:

Files.writeString(Paths.get(file.toURI()), 
                  "My string to save", 
                   StandardCharsets.UTF_8,
                   StandardOpenOption.CREATE,
                   StandardOpenOption.TRUNCATE_EXISTING);

ORIGINAL ANSWER:

There is a one-line solution, using Java nio:

java.nio.file.Files.write(Paths.get(file.toURI()), 
                          "My string to save".getBytes(StandardCharsets.UTF_8),
                          StandardOpenOption.CREATE,
                          StandardOpenOption.TRUNCATE_EXISTING);

I have not benchmarked this solution with the others, but using the built-in implementation for open-write-close file should be fast and the code is quite small.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)