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

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.file) exposes these flags as values of the OpenOption interface. Most of them live in the enum StandardOpenOption; LinkOption.NOFOLLOW_LINKS is the other common one. On Linux and macOS the JDK turns them into flags of the open system call almost one to one: CREATE is O_CREAT, CREATE_NEW is O_CREAT | O_EXCL, TRUNCATE_EXISTING is O_TRUNC and APPEND is O_APPEND.

That mapping explains most of the behavior on this page. The checks happen inside the operating system in a single step, so CREATE_NEW is atomic and APPEND is safe for several writers. It also explains why some combinations make no sense and are rejected before the file is touched.

The StandardOpenOption values
OptionEffectTypical use
READOpen for readingDefault for every reading method
WRITEOpen for writing, starting at byte 0, without truncatingUpdating a file in place
APPENDEvery write goes to the current end of the fileLogs and journals
TRUNCATE_EXISTINGCut an existing file to 0 bytes, if opened for writingReplacing content
CREATECreate the file if it does not existOutput files that may or may not exist
CREATE_NEWCreate the file; fail if it existsNever overwriting; marker files
DELETE_ON_CLOSEDelete the file when it is closed (best effort)Scratch files used by one JVM
SPARSEHint that a new file will be sparse; only with CREATE_NEWHuge files with large empty regions
SYNCEach write of content and metadata reaches the storage device before returningData that must survive a crash
DSYNCLike SYNC, for content onlyThe same, slightly cheaper in theory

These methods accept options: Files.write, Files.writeString, Files.newOutputStream, Files.newBufferedWriter, Files.newInputStream, Files.newByteChannel, FileChannel.open and AsynchronousFileChannel.open. Files.newBufferedReader takes none, since it only reads. The older java.io classes have no options at all; they use a boolean or a mode string, shown near the end.

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:

Options used when you pass none
MethodDefault options
Files.writeString, Files.writeCREATE, TRUNCATE_EXISTING, WRITE
Files.newOutputStream, Files.newBufferedWriterCREATE, TRUNCATE_EXISTING, WRITE
Files.newInputStreamREAD
Files.newByteChannel, FileChannel.openREAD

As soon as you pass any option, the defaults are gone and you get exactly the set you passed. The writing methods add WRITE for you, but nothing else. The program writes short strings of different lengths into one file, so you can see which bytes were replaced and which survived, and then tries the same options on files that do not exist.

Java
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:

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 CREATE plus TRUNCATE_EXISTING at work.
  • WRITE alone does not truncate. "XY" overwrote bytes 0 and 1 and left "c+++" in place, giving "XYc+++". Forgetting TRUNCATE_EXISTING 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.
  • The same trap with CREATE: passing only CREATE turned "new" into "New". Many developers expect CREATE to mean "create or replace", but replacing needs TRUNCATE_EXISTING too.
  • CREATE_NEW refused to touch the existing file and threw FileAlreadyExistsException.
  • On missing files, both WRITE and APPEND threw NoSuchFileException, because neither implies CREATE. A log writer that calls writeString(p, line, APPEND) works on the developer's machine, where the file exists, and fails on a fresh server. Use CREATE, APPEND.
  • Only the two calls that included CREATE or CREATE_NEW produced files, which is why the final listing has c.txt and d.txt but no a.txt or b.txt.

APPEND versus WRITE when several writers share a file

APPEND is more than "start at the end". With it, the operating system moves to the current end of the file and writes there in one step, for every single write. With WRITE, each open file has its own position that starts at 0. To see the difference, the program opens the same file twice, as two processes writing one log would, and writes three short records through each.

Java
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:

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 WRITE, 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 without APPEND.
  • With APPEND, 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.
  • On an APPEND channel, position(0) is accepted but has no effect on writing: "Z" still went to the end and the position became 20. The FileChannel Javadoc says the same: in append mode the position is advanced to the end of the file before each write.
  • Each write 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 per write call.

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.

Java
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:

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)
  • APPEND with READ, and APPEND with TRUNCATE_EXISTING, throw IllegalArgumentException before the file is opened.
  • The stream methods check the direction. Files.newOutputStream and Files.writeString reject READ with IllegalArgumentException, while Files.newInputStream rejects WRITE with UnsupportedOperationException. The two exceptions are unrelated, so catching one does not catch the other.
  • TRUNCATE_EXISTING on a channel opened only for reading is ignored, as its Javadoc says: the file still has 5 bytes.
  • CREATE is also ignored when the file is opened only for reading, so newByteChannel(missing, CREATE) threw NoSuchFileException. Add WRITE to actually create the file.
  • When CREATE and CREATE_NEW are both present, CREATE_NEW wins and the call fails on an existing file.

CREATE_NEW as an atomic test, and the DELETE_ON_CLOSE trap

Checking Files.exists and then creating the file is a race: two processes can both see "missing" and both create it. CREATE_NEW does the check and the creation as one operation in the operating system, so exactly one caller can succeed. The program starts eight threads at the same moment with a latch, all trying to create the same lock file. It then shows why DELETE_ON_CLOSE must not be used to remove such a lock.

Java
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:

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 FileAlreadyExistsException. The same holds across separate processes, which makes CREATE_NEW (or Files.createFile, 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.
  • With DELETE_ON_CLOSE, 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 second CREATE_NEW therefore succeeded while the first "lock" was still held, which defeats the purpose.
  • After both channels were closed, a file still existed: the second one, which had no DELETE_ON_CLOSE. On Windows the behavior differs, because there the file stays visible until it is closed.

The Javadoc describes DELETE_ON_CLOSE as intended for work files used by a single JVM, and not recommended for files that other programs open at the same time. For in-process scratch data it is convenient: the file disappears even if your code forgets to delete it, and the JVM also tries to delete it on exit. For locks that coordinate processes, FileChannel.lock() is the tool; see NIO channels.

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 write returned. DSYNC makes every write wait until the content reaches the storage device, and SYNC also waits for metadata such as the file length and modification time. The program writes 500 small payment records four ways, best of 3 runs each. It writes to the working directory rather than /tmp, which is a RAM disk on many Linux systems and would make syncing free.

Java
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):

Output
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 force(false), 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.
  • DSYNC and SYNC 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.
  • The difference between SYNC and DSYNC 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.

The practical rule: use SYNC or DSYNC only when each individual write must be durable before the program continues, such as a transaction log that confirms each payment. When it is enough that a batch is durable, write normally and call FileChannel.force once at the commit point. Writing a temporary file and moving it into place, shown on the text file writing page, covers the other common need: readers never see a half-written file.

Symbolic links, and the java.io equivalents

By default, opening a symbolic link opens the file it points to. LinkOption.NOFOLLOW_LINKS refuses to follow the link. That matters for programs that write into directories other users control, where a planted link could redirect a write to another file. The second half of the program shows how the older java.io classes express the same choices without options.

Java
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:

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 real.txt. With NOFOLLOW_LINKS 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.
  • FileOutputStream has a single switch. new FileOutputStream(f, true) behaves like CREATE, APPEND, so "+more" was added. new FileOutputStream(f) behaves like CREATE, TRUNCATE_EXISTING, WRITE, so the file was replaced by "gone". There is no java.io way to say "fail if it exists"; that needs CREATE_NEW.
  • RandomAccessFile takes a mode string. "r" is read-only and fails with FileNotFoundException on a missing file. "rw" reads, writes and creates the file, and never truncates. "rws" and "rwd" add the equivalents of SYNC and DSYNC. Any other string, such as "w", throws IllegalArgumentException. More on this class on the RandomAccessFile page.

Which options to use

Choosing open options
GoalOptions
Write a file, replacing any old contentNone (the defaults), or CREATE, TRUNCATE_EXISTING, WRITE
Add to a log that may not exist yetCREATE, APPEND
Several processes appending to one fileCREATE, APPEND, one record per write call
Never overwrite an existing fileCREATE_NEW, WRITE
Only one process may run a jobA CREATE_NEW marker file that you delete yourself, or FileChannel.lock()
Change bytes in placeREAD, WRITE, without TRUNCATE_EXISTING
Scratch file for this JVM onlyCREATE_NEW, WRITE, DELETE_ON_CLOSE, or Files.createTempFile
Every write durable before continuingDSYNC or SYNC; otherwise one force() per batch
Do not follow a planted symbolic linkAdd LinkOption.NOFOLLOW_LINKS

For complete reading and writing programs, see writing a text file and reading a text file.