Writing Bytes: Files.write with byte[]
You'll learn how to write a byte array directly to a file using Files.write() and control file creation behavior with options.
The Core Idea
While Files.readAllBytes lets you slurp an entire file into a byte array, Files.write() does the reverse—it takes a byte array and writes it to a file in one operation. But here's where it gets powerful: you can specify options that control exactly how the file should be created or modified.
Think of it like configuring a copy machine: do you want to replace the existing document completely (TRUNCATE_EXISTING), add to the end of it (APPEND), or create a new one if none exists (CREATE)?
The Basic Syntax
Path path = Paths.get("output.bin");
byte[] data = {72, 101, 108, 108, 111}; // "Hello" in ASCII
// Write with CREATE and TRUNCATE_EXISTING (default behavior)
Files.write(path, data);
Controlling Write Behavior with Options
import java.nio.file.*;
import static java.nio.file.StandardOpenOption.*;
// Create new file or replace existing one completely
Files.write(path, data, CREATE, TRUNCATE_EXISTING);
// Append to existing file (or create if doesn't exist)
Files.write(path, data, CREATE, APPEND);
// Only create if file doesn't exist (throws exception if exists)
Files.write(path, data, CREATE_NEW);
The options are like instructions to the file system: CREATE says "make it if it's missing," TRUNCATE_EXISTING says "erase what's there first," and APPEND says "add to the end."
Practical Example
Path log = Paths.get("app.log");
byte[] logEntry = "New event logged\n".getBytes();
// Append to log file
Files.write(log, logEntry, CREATE, APPEND);
Key Takeaway: Files.write() writes a byte array to a file with options like CREATE, TRUNCATE_EXISTING, and APPEND to control whether you're replacing, appending, or creating files—making file operations both simple and flexible.