Reputation: 237
Probably a simple answer but I've tried reading the javadoc documentation on StandardOpenOption but I'm still unclear of what happens when I say
Files.write(..., ..., StandardOpenOption.WRITE, StandardOpenOption.CREATE); // Write A
Based on some local tests, it looks like this will still overwrite the file if it exists already, so what is the difference between the above and
Files.write(..., ..., StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); // Write B
?
Furthermore, I have a program with two threads that read/write from the written file. When I use Write B, I sometimes get a race condition where one thread would've created the file, and the other overwrites it while the first thread is reading and I get an exception. But when I use Write A, I never get this race condition. Almost as if it'll lock the file first? Can someone explain what is going on behind the scenes?
Upvotes: 1
Views: 5518
Reputation: 2177
when you use the StandardOpenOption.TRUNCATE_EXISTING
the length of the file is first "truncated to 0" if the file already exist before any writing:
$ jshell
jshell> import java.nio.file.*;
jshell> Path path = Paths.get("foo");
path ==> foo
jshell> Files.write(path, "AAAA".getBytes(), StandardOpenOption.WRITE, StandardOpenOption.CREATE)
I've just create a new file named "foo" containing the string "AAAA":
$ more foo
AAAA
$
now I write the string "BB" to the file without StandardOpenOption.TRUNCATE_EXISTING
option:
jshell> Files.write(path, "BB".getBytes(), StandardOpenOption.WRITE, StandardOpenOption.CREATE)
and just the first two characters gets overwritten, the others are still there:
$ more foo
BBAA
$
now I write the string "BB" again but I add StandardOpenOption.TRUNCATE_EXISTING
option:
jshell> Files.write(path, "BB".getBytes(), StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)
the file contains just "BB" because its previous content has been "erased" by StandardOpenOption.TRUNCATE_EXISTING
before the writing:
$ more foo
BB
$
Upvotes: 8