OpenOption: Controlling Write Behavior
What you'll learn: How to use StandardOpenOption constants to precisely control file creation and writing behavior in NIO.2.
When you write to a file using NIO.2 methods like Files.write or Files.newBufferedWriter, you can specify how the file should be opened. Should it create a new file? Overwrite an existing one? Append to it? These behaviors are controlled by passing OpenOption parameters—specifically, constants from the StandardOpenOption enum.
The Core Options
CREATE: Creates the file if it doesn't exist. If the file already exists, this option alone does nothing special (the file is opened).
TRUNCATE_EXISTING: If the file exists, truncate it to zero length (erasing all previous content) before writing. This is like starting with a blank slate.
APPEND: Writes are added to the end of the file rather than overwriting from the beginning. Perfect for log files or accumulating data.
Think of It Like a Notebook
Imagine you're writing in a notebook:
- CREATE: "If there's no notebook with this name, make one."
- TRUNCATE_EXISTING: "Rip out all the old pages before I start writing."
- APPEND: "Start writing after the last thing I wrote, don't erase anything."
Using Options in Code
Path logFile = Paths.get("app.log");
// Append to existing file, create if doesn't exist
Files.writeString(logFile, "New log entry\n",
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
// Overwrite file completely
Files.writeString(logFile, "Fresh start",
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
If you don't specify options, Files.write and writeString default to CREATE and TRUNCATE_EXISTING—overwriting the file.
Key Takeaway: Use StandardOpenOption constants (CREATE, TRUNCATE_EXISTING, APPEND) to control whether files are created, overwritten, or appended to, giving you precise control over write behavior in NIO.2.