Home Java Files Methods write() Java Files write() Method Definition In Java, Files.write saves data to a file in a single call. One overload takes a byte[]; the others take an Iterable of lines (for example a List<String>) and write each one followed by the platform line separator .
With no options it behaves like CREATE, TRUNCATE_EXISTING, and WRITE: the file is created if needed and any old content is replaced . Pass StandardOpenOption.APPEND to add to the end instead.
A static method of the final utility class java.nio.file.Files, available since Java 7. Call it on the class name, as in Files.write(...), after import java.nio.file.Files;. You never create a Files object.
Syntax Bytes or lines, plus optional charset and options:
Files.write(path, bytes); // replace
Files.write(path, lines); // UTF-8 lines (Java 8)
Files.write(path, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND); Call What it does Files.write(p, bytes)Replace the file with these bytes. Files.write(p, lines)One line per element, UTF-8. Files.write(p, lines, cs, APPEND)Add lines to the end. Files.write(p, b, CREATE_NEW)Fail if the file already exists.
Since Java 7; the lines overload without a charset arrived in Java 8. Returns the path, so calls can be chained.
Library declarations public static Path write(Path path, byte[] bytes, OpenOption... options) throws IOException
public static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options) throws IOException
public static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options) throws IOException Parameters Parameter Description pathThe file to write. bytes / linesThe data: raw bytes, or text lines written one per line. csCharset for encoding the lines (UTF-8 if omitted). optionsAPPEND, CREATE, CREATE_NEW, TRUNCATE_EXISTING, SYNC, and more.
Return Value Return Value Description PathThe same path you passed in.
Important
The parent folder must exist, otherwise NoSuchFileException. CREATE_NEW throws FileAlreadyExistsException for an existing file, and an unmappable character in a line throws UnmappableCharacterException. Because the line separator is \r\n on Windows and \n elsewhere, a file written from lines has a different size on Windows.
Compare with Similar Methods Writing options:
Java Examples 1. Bytes and lines 2. Replace vs append 3. Charset and CREATE_NEW Example 1 — Save Bytes and Save Lines The byte overload writes exactly what you give it; the lines overload adds a separator after each line.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
public class WriteBytesAndLines {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("demo");
Path raw = dir.resolve("raw.txt");
Path list = dir.resolve("list.txt");
Files.write(raw, "Hello".getBytes(StandardCharsets.UTF_8));
Files.write(list, Arrays.asList("milk", "eggs", "bread"));
System.out.println("raw.txt size: " + Files.size(raw));
System.out.println("list.txt lines: " + Files.readAllLines(list));
Files.delete(raw);
Files.delete(list);
Files.delete(dir);
}
} Run with java WriteBytesAndLines. The output is the same on Windows, macOS, and Linux.
raw.txt size: 5
list.txt lines: [milk, eggs, bread] How It Works Exact bytes. "Hello" encodes to five UTF-8 bytes and nothing is added, so the size is 5 everywhere.Lines get separators. Each list element is followed by the system line separator, so list.txt ends with a line break too.Size deliberately not printed. list.txt is 16 bytes on Linux and macOS but 19 on Windows; reading it back as lines gives the same list on both.Example 2 — Default Replaces, APPEND Adds Write, append, then write again without options to see the old content disappear.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Collections;
public class WriteAppend {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("demo");
Path log = dir.resolve("log.txt");
Files.write(log, Collections.singletonList("first"));
Files.write(log, Collections.singletonList("second"), StandardOpenOption.APPEND);
System.out.println("After append: " + Files.readAllLines(log));
Files.write(log, Collections.singletonList("third"));
System.out.println("After plain write: " + Files.readAllLines(log));
Files.delete(log);
Files.delete(dir);
}
} Run with java WriteAppend. The output is the same on Windows, macOS, and Linux.
After append: [first, second]
After plain write: [third] How It Works Create. The first call creates log.txt with one line.Append. APPEND moves to the end before writing, so "second" lands after "first".Replace. The third call has no options, so the default TRUNCATE_EXISTING empties the file before writing "third".Example 3 — Pick an Encoding and Refuse to Overwrite Write a line in ISO-8859-1 with CREATE_NEW, inspect the encoded byte, then try to create the file again.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;
public class WriteCharsetCreateNew {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("demo");
Path menu = dir.resolve("menu.txt");
List<String> lines = Arrays.asList("caf\u00e9");
Files.write(menu, lines, StandardCharsets.ISO_8859_1, StandardOpenOption.CREATE_NEW);
byte[] data = Files.readAllBytes(menu);
System.out.println("Byte for e-acute: " + (data[3] & 0xFF));
try {
Files.write(menu, lines, StandardCharsets.ISO_8859_1, StandardOpenOption.CREATE_NEW);
} catch (FileAlreadyExistsException e) {
System.out.println("Second CREATE_NEW: FileAlreadyExistsException");
}
Files.delete(menu);
Files.delete(dir);
}
} Run with java WriteCharsetCreateNew. The output is the same on Windows, macOS, and Linux.
Byte for e-acute: 233
Second CREATE_NEW: FileAlreadyExistsException How It Works ASCII source, accented text. \u00e9 is a Unicode escape for e-acute, so the source file stays plain ASCII.One byte per character. ISO-8859-1 stores e-acute as the single byte 233 (0xE9); UTF-8 would need two bytes.No accidental overwrite. CREATE_NEW makes the second call fail instead of replacing menu.txt.Frequently Asked Questions How do I write a String to a file in Java 8? Files.write(path, text.getBytes(StandardCharsets.UTF_8)). Java 11 also offers Files.writeString(path, text).
Does Files.write overwrite the existing file? Yes, by default. Without options it uses CREATE, TRUNCATE_EXISTING, and WRITE.
How do I append to a file with Files.write? Pass StandardOpenOption.APPEND, plus CREATE if the file might not exist yet.
Which line separator does Files.write use for lines? The platform line separator: \r\n on Windows, \n on Linux and macOS.
Does Files.write create parent directories? No. Call Files.createDirectories(path.getParent()) first, or you get NoSuchFileException.
Next: Files.writeString() Write a String or other CharSequence to a file, UTF-8 by default (Java 11+).
writeString() tutorial → About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
10 people found this page helpful
Helpful Share Copy link Suggestion