File Open Options in Java
When Java's NIO API opens a file, OpenOption values decide whether it is created, replaced, appended to or opened for reading, and how durable each write is. Each method has its own defaults, some options are ignored in some contexts, and a few combinations are rejected. This page runs each option on real files, including several writers sharing one file and the cost of SYNC.
Contents
What open options are and how they work Defaults, and why passing one option changes everything APPEND versus WRITE when several writers share a file Combinations that fail, and options that are silently ignored CREATE_NEW as an atomic test, and the DELETE_ON_CLOSE trap SYNC and DSYNC: what durability costs Symbolic links, and the java.io equivalents Which options to use
What open options are and how they work
Before a program can read or write a file, it asks the operating system to open it, and the request carries a few flags: open for reading or writing, create the file if it is missing, fail if it exists, cut it to zero length, send every write to the end. Java's NIO API (Java 7, java.nio.fileOpenOptionStandardOpenOptionLinkOption.NOFOLLOW_LINKSopenCREATEO_CREATCREATE_NEWO_CREAT | O_EXCLTRUNCATE_EXISTINGO_TRUNCAPPENDO_APPEND
That mapping explains most of the behavior on this page. The checks happen inside the operating system in a single step, so CREATE_NEWAPPEND
| Option | Effect | Typical use |
|---|---|---|
READ | Open for reading | Default for every reading method |
WRITE | Open for writing, starting at byte 0, without truncating | Updating a file in place |
APPEND | Every write goes to the current end of the file | Logs and journals |
TRUNCATE_EXISTING | Cut an existing file to 0 bytes, if opened for writing | Replacing content |
CREATE | Create the file if it does not exist | Output files that may or may not exist |
CREATE_NEW | Create the file; fail if it exists | Never overwriting; marker files |
DELETE_ON_CLOSE | Delete the file when it is closed (best effort) | Scratch files used by one JVM |
SPARSE | Hint that a new file will be sparse; only with CREATE_NEW | Huge files with large empty regions |
SYNC | Each write of content and metadata reaches the storage device before returning | Data that must survive a crash |
DSYNC | Like SYNC | The same, slightly cheaper in theory |
These methods accept options: Files.writeFiles.writeStringFiles.newOutputStreamFiles.newBufferedWriterFiles.newInputStreamFiles.newByteChannelFileChannel.openAsynchronousFileChannel.openFiles.newBufferedReaderjava.io
All programs below were compiled and run on JDK 21 on Linux. Each one uses its own temporary files.
Defaults, and why passing one option changes everything
Each method has default options that apply only when you pass none:
| Method | Default options |
|---|---|
Files.writeStringFiles.write | CREATETRUNCATE_EXISTINGWRITE |
Files.newOutputStreamFiles.newBufferedWriter | CREATETRUNCATE_EXISTINGWRITE |
Files.newInputStream | READ |
Files.newByteChannelFileChannel.open | READ |
As soon as you pass any option, the defaults are gone and you get exactly the set you passed. The writing methods add WRITE
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.util.Arrays;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.CREATE_NEW;
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
import static java.nio.file.StandardOpenOption.WRITE;
public class CreateAndReplace {
static void write(Path p, String text, OpenOption... options) throws IOException {
String label = options.length == 0 ? "(none: defaults)" : Arrays.toString(options);
try {
Files.writeString(p, text, options);
System.out.printf("%-28s write %-6s -> \"%s\"%n",
label, "\"" + text + "\"", Files.readString(p));
} catch (FileAlreadyExistsException | NoSuchFileException e) {
System.out.printf("%-28s write %-6s -> %s%n",
label, "\"" + text + "\"", e.getClass().getSimpleName());
}
}
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("open-options");
Path p = dir.resolve("data.txt");
System.out.println("-- existing file data.txt --");
write(p, "HELLO"); // creates the file
write(p, "abc"); // replaces everything
write(p, "+++", APPEND); // adds at the end
write(p, "XY", WRITE); // overwrites from byte 0 only
write(p, "new", WRITE, TRUNCATE_EXISTING); // empties first
write(p, "N", CREATE); // CREATE alone: no truncation
write(p, "x", CREATE_NEW); // refuses: file exists
System.out.println("-- missing files --");
write(dir.resolve("a.txt"), "x", WRITE); // no CREATE
write(dir.resolve("b.txt"), "x", APPEND); // no CREATE either
write(dir.resolve("c.txt"), "x", CREATE, APPEND);
write(dir.resolve("d.txt"), "x", CREATE_NEW, WRITE);
try (var files = Files.list(dir)) {
System.out.println("files now: " + files.map(f -> f.getFileName().toString())
.sorted().toList());
}
}
}
Output:
-- existing file data.txt --
(none: defaults) write "HELLO" -> "HELLO"
(none: defaults) write "abc" -> "abc"
[APPEND] write "+++" -> "abc+++"
[WRITE] write "XY" -> "XYc+++"
[WRITE, TRUNCATE_EXISTING] write "new" -> "new"
[CREATE] write "N" -> "New"
[CREATE_NEW] write "x" -> FileAlreadyExistsException
-- missing files --
[WRITE] write "x" -> NoSuchFileException
[APPEND] write "x" -> NoSuchFileException
[CREATE, APPEND] write "x" -> "x"
[CREATE_NEW, WRITE] write "x" -> "x"
files now: [c.txt, d.txt, data.txt]
- With no options, the first call created the file and the second replaced "HELLO" completely with "abc". That is
plusCREATE at work.TRUNCATE_EXISTING alone does not truncate. "XY" overwrote bytes 0 and 1 and left "c+++" in place, giving "XYc+++". ForgettingWRITE when writing a shorter version of a file is a classic cause of corrupted configuration files, because the end of the old content stays behind.TRUNCATE_EXISTING- The same trap with
: passing onlyCREATE turned "new" into "New". Many developers expectCREATE to mean "create or replace", but replacing needsCREATE too.TRUNCATE_EXISTING refused to touch the existing file and threwCREATE_NEW .FileAlreadyExistsException- On missing files, both
andWRITE threwAPPEND , because neither impliesNoSuchFileException . A log writer that callsCREATE works on the developer's machine, where the file exists, and fails on a fresh server. UsewriteString(p, line, APPEND) .CREATE, APPEND - Only the two calls that included
orCREATE produced files, which is why the final listing hasCREATE_NEW andc.txt but nod.txt ora.txt .b.txt
APPEND versus WRITE when several writers share a file
APPENDWRITE
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.WRITE;
public class AppendVsWrite {
// Two writers share one file, as two processes writing one log would.
static void twoWriters(Path p, OpenOption... options) throws IOException {
Files.deleteIfExists(p);
try (FileChannel a = FileChannel.open(p, options);
FileChannel b = FileChannel.open(p, options)) {
for (int i = 1; i <= 3; i++) {
a.write(bytes("A" + i + "\n"));
b.write(bytes("B" + i + "\n"));
}
}
String content = Files.readString(p).replace("\n", " ");
System.out.printf("%-17s size %2d bytes: %s%n",
options[options.length - 1], Files.size(p), content);
}
static ByteBuffer bytes(String s) {
return ByteBuffer.wrap(s.getBytes(StandardCharsets.US_ASCII));
}
public static void main(String[] args) throws IOException {
Path p = Files.createTempFile("shared-log", ".txt");
twoWriters(p, CREATE, WRITE);
twoWriters(p, CREATE, APPEND);
// With APPEND, the position you ask for is ignored
try (FileChannel ch = FileChannel.open(p, APPEND)) {
ch.position(0);
ch.write(bytes("Z\n"));
System.out.println("after position(0) + write: position " + ch.position()
+ ", file ends with " + Files.readString(p).strip().lines()
.reduce((x, y) -> y).orElseThrow());
}
Files.delete(p);
}
}
Output:
WRITE size 9 bytes: B1 B2 B3
APPEND size 18 bytes: A1 B1 A2 B2 A3 B3
after position(0) + write: position 20, file ends with Z
- With
, both channels started at position 0 and moved forward independently. Every "B" record landed on the bytes the "A" record had just written, so only 9 bytes survived: "B1 B2 B3". No error was reported. The same silent loss happens when two programs open one log withoutWRITE .APPEND - With
, all six 3-byte records are there, 18 bytes, in the order they were written. Each write went to the end as it was at that moment.APPEND - On an
channel,APPEND is accepted but has no effect on writing: "Z" still went to the end and the position became 20. Theposition(0) Javadoc says the same: in append mode the position is advanced to the end of the file before each write.FileChannel - Each
call is placed as a unit, but a buffered writer issues its own writes whenever its buffer fills, so one logical record can be split across two system calls. When several processes append to one file, keep one record perwrite call.write
Combinations that fail, and options that are silently ignored
Some combinations contradict each other, and some options do nothing in a given context. The program tries both kinds and prints what the JDK does with each one.
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.CREATE_NEW;
import static java.nio.file.StandardOpenOption.READ;
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
import static java.nio.file.StandardOpenOption.WRITE;
public class InvalidCombinations {
interface Attempt {
void run() throws IOException;
}
static void attempt(String label, Attempt a) {
try {
a.run();
System.out.printf("%-42s -> ok%n", label);
} catch (Exception e) {
System.out.printf("%-42s -> %s: %s%n", label,
e.getClass().getSimpleName(), e.getMessage().replaceAll("/tmp/\\S+/", ""));
}
}
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("combos");
Path p = dir.resolve("data.txt");
Files.writeString(p, "12345");
System.out.println("-- rejected outright --");
attempt("FileChannel.open APPEND, READ", () -> FileChannel.open(p, APPEND, READ).close());
attempt("FileChannel.open APPEND, TRUNCATE_EXISTING",
() -> FileChannel.open(p, APPEND, TRUNCATE_EXISTING).close());
attempt("Files.newOutputStream READ", () -> Files.newOutputStream(p, READ).close());
attempt("Files.newInputStream WRITE", () -> Files.newInputStream(p, WRITE).close());
attempt("Files.writeString READ", () -> Files.writeString(p, "x", READ));
System.out.println("-- accepted but ignored --");
attempt("FileChannel.open TRUNCATE_EXISTING",
() -> FileChannel.open(p, TRUNCATE_EXISTING).close());
System.out.println(" size afterwards: " + Files.size(p) + " (not truncated)");
Path missing = dir.resolve("missing.txt");
attempt("Files.newByteChannel CREATE (no WRITE)",
() -> Files.newByteChannel(missing, CREATE).close());
attempt("FileChannel.open CREATE, CREATE_NEW, WRITE",
() -> FileChannel.open(p, CREATE, CREATE_NEW, WRITE).close());
System.out.println(" (CREATE is ignored when CREATE_NEW is present)");
Files.delete(p);
Files.delete(dir);
}
}
Output:
-- rejected outright --
FileChannel.open APPEND, READ -> IllegalArgumentException: READ + APPEND not allowed
FileChannel.open APPEND, TRUNCATE_EXISTING -> IllegalArgumentException: APPEND + TRUNCATE_EXISTING not allowed
Files.newOutputStream READ -> IllegalArgumentException: READ not allowed
Files.newInputStream WRITE -> UnsupportedOperationException: 'WRITE' not allowed
Files.writeString READ -> IllegalArgumentException: READ not allowed
-- accepted but ignored --
FileChannel.open TRUNCATE_EXISTING -> ok
size afterwards: 5 (not truncated)
Files.newByteChannel CREATE (no WRITE) -> NoSuchFileException: missing.txt
FileChannel.open CREATE, CREATE_NEW, WRITE -> FileAlreadyExistsException: data.txt
(CREATE is ignored when CREATE_NEW is present)
withAPPEND , andREAD withAPPEND , throwTRUNCATE_EXISTING before the file is opened.IllegalArgumentException- The stream methods check the direction.
andFiles.newOutputStream rejectFiles.writeString withREAD , whileIllegalArgumentException rejectsFiles.newInputStream withWRITE . The two exceptions are unrelated, so catching one does not catch the other.UnsupportedOperationException on a channel opened only for reading is ignored, as its Javadoc says: the file still has 5 bytes.TRUNCATE_EXISTING is also ignored when the file is opened only for reading, soCREATE threwnewByteChannel(missing, CREATE) . AddNoSuchFileException to actually create the file.WRITE- When
andCREATE are both present,CREATE_NEW wins and the call fails on an existing file.CREATE_NEW
CREATE_NEW as an atomic test, and the DELETE_ON_CLOSE trap
Checking Files.existsCREATE_NEWDELETE_ON_CLOSE
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import static java.nio.file.StandardOpenOption.CREATE_NEW;
import static java.nio.file.StandardOpenOption.DELETE_ON_CLOSE;
import static java.nio.file.StandardOpenOption.WRITE;
public class CreateNewLock {
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("lock-demo");
Path lock = dir.resolve("job.lock");
// 1. Eight threads try to create the same file at the same moment
AtomicInteger won = new AtomicInteger();
AtomicInteger lost = new AtomicInteger();
CountDownLatch start = new CountDownLatch(1);
Thread[] threads = new Thread[8];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
try {
start.await();
FileChannel.open(lock, CREATE_NEW, WRITE).close();
won.incrementAndGet();
} catch (FileAlreadyExistsException e) {
lost.incrementAndGet();
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
});
threads[i].start();
}
start.countDown();
for (Thread t : threads) {
t.join();
}
System.out.println("CREATE_NEW race: " + won + " winner, " + lost
+ " FileAlreadyExistsException");
Files.delete(lock);
// 2. The trap: DELETE_ON_CLOSE on a lock file
try (FileChannel held = FileChannel.open(lock, CREATE_NEW, WRITE, DELETE_ON_CLOSE)) {
System.out.println("lock held (open: " + held.isOpen() + "), file visible: "
+ Files.exists(lock));
try (FileChannel second = FileChannel.open(lock, CREATE_NEW, WRITE)) {
System.out.println("second CREATE_NEW while the lock is held: succeeded, open: "
+ second.isOpen());
}
}
System.out.println("after both closed, file exists: " + Files.exists(lock));
Files.delete(lock);
Files.delete(dir);
}
}
Output:
CREATE_NEW race: 1 winner, 7 FileAlreadyExistsException
lock held (open: true), file visible: false
second CREATE_NEW while the lock is held: succeeded, open: true
after both closed, file exists: true
- Of the eight threads, one created the file and the other seven got
. The same holds across separate processes, which makesFileAlreadyExistsException (orCREATE_NEW , which uses it) suitable for "only one instance runs this job" marker files. A crashed process leaves the file behind, so real marker files usually also store a process ID or a time so that stale ones can be detected.Files.createFile - With
, the file was not visible even while the lock was held. On Linux the JDK deletes the name right after opening and keeps the data reachable only through the open channel. A secondDELETE_ON_CLOSE therefore succeeded while the first "lock" was still held, which defeats the purpose.CREATE_NEW - After both channels were closed, a file still existed: the second one, which had no
. On Windows the behavior differs, because there the file stays visible until it is closed.DELETE_ON_CLOSE
The Javadoc describes DELETE_ON_CLOSEFileChannel.lock()
SYNC and DSYNC: what durability costs
A normal write returns as soon as the data is in the operating system's page cache; the disk is updated later. If the machine loses power in between, the data is lost even though writeDSYNCSYNC/tmp
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.util.Arrays;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.DSYNC;
import static java.nio.file.StandardOpenOption.SYNC;
import static java.nio.file.StandardOpenOption.WRITE;
public class SyncCost {
static final int RECORDS = 500;
static long run(Path p, boolean forceAtEnd, OpenOption... options) throws IOException {
Files.deleteIfExists(p);
long start = System.nanoTime();
try (FileChannel ch = FileChannel.open(p, options)) {
for (int i = 0; i < RECORDS; i++) {
ch.write(ByteBuffer.wrap(("payment " + i + " ok\n")
.getBytes(StandardCharsets.US_ASCII)));
}
if (forceAtEnd) {
ch.force(false);
}
}
return System.nanoTime() - start;
}
static void measure(String label, Path p, boolean force, OpenOption... options)
throws IOException {
long best = Long.MAX_VALUE;
for (int r = 0; r < 3; r++) {
best = Math.min(best, run(p, force, options));
}
System.out.printf("%-30s %8.1f ms (%s)%n", label, best / 1e6, Arrays.toString(options));
}
public static void main(String[] args) throws IOException {
Path p = Path.of("sync-test.txt"); // a real disk, not a RAM-backed /tmp
for (int warm = 0; warm < 5; warm++) {
run(p, true, CREATE, WRITE); // let the JIT compile the loop first
}
System.out.println(RECORDS + " small writes, best of 3:");
measure("plain WRITE", p, false, CREATE, WRITE);
measure("plain WRITE + one force()", p, true, CREATE, WRITE);
measure("DSYNC (content per write)", p, false, CREATE, WRITE, DSYNC);
measure("SYNC (content + metadata)", p, false, CREATE, WRITE, SYNC);
Files.delete(p);
}
}
Output (rough comparison on a 2-CPU Linux VM with SSD storage, JDK 21; absolute times will differ on yours):
500 small writes, best of 3:
plain WRITE 0.8 ms ([CREATE, WRITE])
plain WRITE + one force() 1.1 ms ([CREATE, WRITE])
DSYNC (content per write) 65.8 ms ([CREATE, WRITE, DSYNC])
SYNC (content + metadata) 62.5 ms ([CREATE, WRITE, SYNC])
- Plain writes, and plain writes followed by one
, both took around a millisecond. Forcing once at the end costs one device flush, which on this machine was too small to separate from the noise.force(false) andDSYNC were roughly 50 to 100 times slower, because every one of the 500 writes waited for the device. On a spinning disk or a network file system the gap is far larger.SYNC- The difference between
andSYNC was within the run-to-run noise. File systems usually have to write metadata anyway when a file grows, and every write here made the file longer.DSYNC
The practical rule: use SYNCDSYNCFileChannel.force
Symbolic links, and the java.io equivalents
By default, opening a symbolic link opens the file it points to. LinkOption.NOFOLLOW_LINKSjava.io
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import static java.nio.file.StandardOpenOption.READ;
public class LinksAndLegacy {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("links");
Path target = dir.resolve("real.txt");
Path link = dir.resolve("link.txt");
Files.writeString(target, "real content");
Files.createSymbolicLink(link, target);
// Following the link is the default
try (var ch = Files.newByteChannel(link, READ)) {
System.out.println("open link normally: " + ch.size() + " bytes of real.txt");
}
try (var ch = Files.newByteChannel(link, READ, LinkOption.NOFOLLOW_LINKS)) {
System.out.println("opened " + ch.size());
} catch (IOException e) {
System.out.println("open with NOFOLLOW_LINKS: " + e.getMessage());
}
// java.io: FileOutputStream has only one switch, append or not
File f = target.toFile();
try (var out = new FileOutputStream(f, true)) {
out.write("+more".getBytes(StandardCharsets.US_ASCII));
}
System.out.println("FileOutputStream(f, true): " + Files.readString(target));
try (var out = new FileOutputStream(f)) {
out.write("gone".getBytes(StandardCharsets.US_ASCII));
}
System.out.println("FileOutputStream(f): " + Files.readString(target));
// java.io: RandomAccessFile uses a mode string instead of options
for (String mode : new String[] {"r", "rw", "rws", "rwd", "w"}) {
Path p = dir.resolve("raf-" + mode + ".bin");
try (var raf = new RandomAccessFile(p.toFile(), mode)) {
System.out.printf("RandomAccessFile mode %-4s -> opened, exists: %b, length %d%n",
mode, Files.exists(p), raf.length());
} catch (IOException | IllegalArgumentException e) {
System.out.printf("RandomAccessFile mode %-4s -> %s%n",
mode, e.getClass().getSimpleName());
}
}
try (var files = Files.list(dir)) {
files.sorted().forEach(p -> {
try {
Files.delete(p);
} catch (IOException e) {
throw new java.io.UncheckedIOException(e);
}
});
}
Files.delete(dir);
}
}
Output:
open link normally: 12 bytes of real.txt
open with NOFOLLOW_LINKS: Too many levels of symbolic links (NOFOLLOW_LINKS specified)
FileOutputStream(f, true): real content+more
FileOutputStream(f): gone
RandomAccessFile mode r -> FileNotFoundException
RandomAccessFile mode rw -> opened, exists: true, length 0
RandomAccessFile mode rws -> opened, exists: true, length 0
RandomAccessFile mode rwd -> opened, exists: true, length 0
RandomAccessFile mode w -> IllegalArgumentException
- Opened normally, the link gave the 12 bytes of
. Withreal.txt the open failed with the operating system's "Too many levels of symbolic links" error. Refusing links is platform dependent; the Javadoc leaves it to the implementation.NOFOLLOW_LINKS has a single switch.FileOutputStream behaves likenew FileOutputStream(f, true) , so "+more" was added.CREATE, APPEND behaves likenew FileOutputStream(f) , so the file was replaced by "gone". There is noCREATE, TRUNCATE_EXISTING, WRITE way to say "fail if it exists"; that needsjava.io .CREATE_NEW takes a mode string. "r" is read-only and fails withRandomAccessFile on a missing file. "rw" reads, writes and creates the file, and never truncates. "rws" and "rwd" add the equivalents ofFileNotFoundException andSYNC . Any other string, such as "w", throwsDSYNC . More on this class on theIllegalArgumentExceptionRandomAccessFile page .
Which options to use
| Goal | Options |
|---|---|
| Write a file, replacing any old content | None (the defaults), or CREATE, TRUNCATE_EXISTING, WRITE |
| Add to a log that may not exist yet | CREATE, APPEND |
| Several processes appending to one file | CREATE, APPEND |
| Never overwrite an existing file | CREATE_NEW, WRITE |
| Only one process may run a job | A CREATE_NEWFileChannel.lock() |
| Change bytes in place | READ, WRITETRUNCATE_EXISTING |
| Scratch file for this JVM only | CREATE_NEW, WRITE, DELETE_ON_CLOSEFiles.createTempFile |
| Every write durable before continuing | DSYNCSYNCforce() |
| Do not follow a planted symbolic link | Add LinkOption.NOFOLLOW_LINKS |
For complete reading and writing programs, see