Java Files write() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 7+

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:

Java
Files.write(path, bytes);                                    // replace
Files.write(path, lines);                                    // UTF-8 lines (Java 8)
Files.write(path, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
CallWhat 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
Java
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

ParameterDescription
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 ValueDescription
PathThe same path you passed in.

Compare with Similar Methods

Writing options:

MethodHow it differs
writeString()Java 11; one string, no added separators.
newBufferedWriter()Write text gradually.
readAllLines()Read the lines back.

Java Examples

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.

Java
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);
    }
}

How It Works

  1. Exact bytes. "Hello" encodes to five UTF-8 bytes and nothing is added, so the size is 5 everywhere.
  2. Lines get separators. Each list element is followed by the system line separator, so list.txt ends with a line break too.
  3. 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.

Java
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);
    }
}

How It Works

  1. Create. The first call creates log.txt with one line.
  2. Append. APPEND moves to the end before writing, so "second" lands after "first".
  3. 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.

Java
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);
    }
}

How It Works

  1. ASCII source, accented text. \u00e9 is a Unicode escape for e-acute, so the source file stays plain ASCII.
  2. One byte per character. ISO-8859-1 stores e-acute as the single byte 233 (0xE9); UTF-8 would need two bytes.
  3. No accidental overwrite. CREATE_NEW makes the second call fail instead of replacing menu.txt.

Frequently Asked Questions

Files.write(path, text.getBytes(StandardCharsets.UTF_8)). Java 11 also offers Files.writeString(path, text).
Yes, by default. Without options it uses CREATE, TRUNCATE_EXISTING, and WRITE.
Pass StandardOpenOption.APPEND, plus CREATE if the file might not exist yet.
The platform line separator: \r\n on Windows, \n on Linux and macOS.
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

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

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