The Files.write
& Files.writeString
methods in Java 7+ are a concise handy way to write text to a file.
try
{
Files.write (
Paths.get ( "/Users/My_UserName/Example.txt" ) ,
List.of( "Hello world" , Instant.now().toString() ) ,
StandardCharsets.UTF_8 ,
StandardOpenOption.WRITE ;
}
catch ( IOException e )
{
throw new RuntimeException ( e );
}
Unfortunately, I cannot get this to work the first time, before the file exists. I get an exception thrown:
java.nio.file.NoSuchFileException
My goal is always blow away any existing file, to write a new fresh file.
I tried adding TRUNCATE_EXISTING
.
try
{
Files.write (
Paths.get ( "/Users/My_UserName/Example.txt" ) ,
List.of( "Hello world" , Instant.now().toString() ) ,
StandardCharsets.UTF_8 ,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING ); // <--- Combining Open-options.
}
catch ( IOException e )
{
throw new RuntimeException ( e );
}
But that too fails when the file does not already exist.
👉🏼 Is there some combination of OpenOption
/StandardOpenOption
objects to make use of these convenient Files
methods?
TRUNCATE_EXISTING, CREATE
together seem to do it – Amaryllidaceous