Java Files: Reading, Writing and Creating Files and Directories
Use java.nio.file.Files for everyday file work: readString, readAllLines, lines and readAllBytes, writeString and write with open options such as APPEND and CREATE_NEW, mismatch, probeContentType, buffered readers and writers, createFile, createDirectory, createDirectories and temporary files.
kvi5hnuCode Sprout team member9 min readOn this page
The Files class is a large collection of static methods that do the real work on the paths from the previous article. This article covers reading and writing file contents and creating files and directories. Article 27 covers copying, moving, deleting and attributes, and article 28 covers listing and walking directories.
Almost every Files method throws an IOException, usually a specific subclass such as NoSuchFileException, FileAlreadyExistsException, DirectoryNotEmptyException or AccessDeniedException. These carry the offending path, which makes error messages far more useful than the false return values of the old File class.
Reading whole files
For files that fit comfortably in memory, one call does it:
byte[] bytes = Files.readAllBytes(path);
String content = Files.readString(path);
List<String> lines = Files.readAllLines(path);
For large files, process lines lazily, and close the stream when done:
try (Stream<String> lines = Files.lines(path)) { ... }
All the text methods use UTF-8 unless you pass a Charset, and unlike the older reader classes, they report malformed input. Reading a Latin-1 file containing é as UTF-8 throws a MalformedInputException instead of producing garbage. Pass the right charset: Files.readString(path, StandardCharsets.ISO_8859_1).
Writing whole files
Files.write(path, bytes);
Files.writeString(path, content);
Files.write(path, lines); // any Iterable<? extends CharSequence>, one line each
By default these create the file if it doesn't exist and truncate it if it does, so the previous contents are replaced. Files.write(path, lines) ends every line, including the last, with the platform line separator. To change the behavior, pass open options:
Files.writeString(path, "another line\n", StandardOpenOption.APPEND);
Files.writeString(path, content, StandardOpenOption.CREATE_NEW); // fail if the file exists
StandardOpenOption | Meaning |
|---|---|
READ, WRITE | open for reading or writing |
APPEND | write at the end of the file |
TRUNCATE_EXISTING | remove existing contents when opening for writing |
CREATE | create the file if it doesn't exist |
CREATE_NEW | create the file, failing with FileAlreadyExistsException if it exists (atomically) |
DELETE_ON_CLOSE | delete the file when it's closed (best effort) |
SPARSE | a hint that the file will be sparse |
SYNC, DSYNC | write every update of content and metadata, or content only, synchronously to the storage device |
When you pass options, you replace the defaults (CREATE, TRUNCATE_EXISTING, WRITE), so APPEND alone fails if the file doesn't exist. Use CREATE, APPEND to append to a file that may not exist yet.
Comparing files and guessing types
Files.mismatch(path1, path2) (Java 12) returns the position of the first byte where two files differ, or -1 if they're identical. It's efficient for checking whether a copy is complete or a file changed.
Files.probeContentType(path) guesses the MIME type, such as "text/plain" or "image/png". It asks the installed FileTypeDetectors, which may look at the file extension, operating system metadata or the first bytes. The result depends on the platform and may be null, so treat it as a hint.
Streams, readers and writers for files
When you need the classic I/O classes, for example to pass to an API that expects a Writer, Files creates them for you, with no need to stack FileOutputStreams and buffers:
InputStream in = Files.newInputStream(path);
OutputStream out = Files.newOutputStream(path);
BufferedReader reader = Files.newBufferedReader(path);
BufferedWriter writer = Files.newBufferedWriter(path);
All accept open options, and the reader and writer methods take an optional Charset, defaulting to UTF-8. BufferedWriter.newLine() writes the platform line separator.
There's also Files.newByteChannel(path, options), which returns a SeekableByteChannel for random access with ByteBuffers, a modern alternative to RandomAccessFile.
Creating files and directories
Files.createDirectory(path); // the parent must exist
Files.createDirectories(path); // creates missing parents too
Files.createFile(path); // an empty file
createDirectorythrowsNoSuchFileExceptionif the parent is missing andFileAlreadyExistsExceptionif the path exists.createDirectoriescreates all missing directories and doesn't complain if the directory already exists, which makes it ideal for "make sure this directory exists".createFilethrowsFileAlreadyExistsExceptionif the file exists. The check and the creation are a single atomic operation, so if two processes race to create the same file, exactly one succeeds. That makes it usable as a simple lock or "claim" mechanism.
All three accept optional FileAttributes, such as POSIX permissions (PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))), applied at creation time. Which attributes are supported depends on the file system.
Files.createLink(link, existing) and Files.createSymbolicLink(link, target) create hard and symbolic links, where the operating system supports them.
Temporary files
Path tempFile = Files.createTempFile(prefix, suffix); // in the system temp directory
Path tempFile = Files.createTempFile(dir, prefix, suffix); // in a given directory
Path tempDir = Files.createTempDirectory(prefix);
Path tempDir = Files.createTempDirectory(dir, prefix);
The name gets a random part between prefix and suffix, such as /tmp/report-8327601934.tmp. Prefix and suffix may be null, and a null suffix means .tmp. The system temp directory is the java.io.tmpdir property. On POSIX systems, temporary files are created readable and writable only by their owner.
Temporary files are not deleted automatically. Delete them yourself, or open them with DELETE_ON_CLOSE. When exactly that deletes the file is platform-dependent: on Unix, the file may be unlinked as soon as it's opened.
A complete example
import java.io.*;
import java.nio.charset.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
import static java.nio.file.StandardOpenOption.*;
public class Solution {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("filesdemo");
Path file = dir.resolve("notes.txt");
// writing whole files
Files.writeString(file, "first line\n");
Files.write(file, List.of("second line", "third line"), APPEND);
Files.writeString(file, "fourth line\n", APPEND);
// reading whole files
System.out.println("readString: " + Files.readString(file).replace("\n", "|"));
System.out.println("readAllLines: " + Files.readAllLines(file));
System.out.println("readAllBytes: " + Files.readAllBytes(file).length + " bytes");
try (Stream<String> lines = Files.lines(file)) {
System.out.println("lines with 'th': " + lines.filter(l -> l.contains("th")).count());
}
// without APPEND, write replaces the contents
Path copy = dir.resolve("copy.txt");
Files.writeString(copy, "something else entirely");
Files.writeString(copy, Files.readString(file));
System.out.println("mismatch after copying content: " + Files.mismatch(file, copy));
Files.writeString(copy, "first line\nsecond LINE\n");
System.out.println("first differing byte: " + Files.mismatch(file, copy));
// CREATE_NEW fails if the file exists
try {
Files.writeString(file, "x", CREATE_NEW);
} catch (FileAlreadyExistsException e) {
System.out.println("CREATE_NEW on an existing file: FileAlreadyExistsException");
}
// stream and reader/writer access
try (BufferedWriter out = Files.newBufferedWriter(dir.resolve("data.csv"))) {
out.write("id,name");
out.newLine();
out.write("1,Ann");
out.newLine();
}
try (BufferedReader in = Files.newBufferedReader(dir.resolve("data.csv"))) {
System.out.println("header: " + in.readLine());
}
try (OutputStream out = Files.newOutputStream(dir.resolve("raw.bin"))) {
out.write(new byte[] { 1, 2, 3 });
}
try (InputStream in = Files.newInputStream(dir.resolve("raw.bin"))) {
System.out.println("raw bytes: " + Arrays.toString(in.readAllBytes()));
}
// encodings: write Latin-1, then read it as UTF-8
Path latin = dir.resolve("latin1.txt");
Files.writeString(latin, "café", StandardCharsets.ISO_8859_1);
try {
Files.readString(latin);
} catch (MalformedInputException e) {
System.out.println("reading Latin-1 as UTF-8: MalformedInputException");
}
System.out.println("with the right charset: " + Files.readString(latin, StandardCharsets.ISO_8859_1));
// creating files and directories
Path sub = dir.resolve("a");
Files.createDirectory(sub);
try {
Files.createDirectory(dir.resolve("x/y/z"));
} catch (NoSuchFileException e) {
System.out.println("createDirectory without parents: NoSuchFileException");
}
Files.createDirectories(dir.resolve("x/y/z"));
Files.createDirectories(dir.resolve("x/y/z")); // no error if it already exists
System.out.println("x/y/z is a directory: " + Files.isDirectory(dir.resolve("x/y/z")));
Path empty = Files.createFile(sub.resolve("empty.txt"));
System.out.println("created " + dir.relativize(empty) + ", size " + Files.size(empty));
try {
Files.createFile(empty);
} catch (FileAlreadyExistsException e) {
System.out.println("createFile twice: FileAlreadyExistsException");
}
// temporary files
Path temp = Files.createTempFile(dir, "report-", ".tmp");
String name = temp.getFileName().toString();
System.out.println("temp file name pattern ok: " + (name.startsWith("report-") && name.endsWith(".tmp")));
Path scratch = dir.resolve("scratch.bin");
try (OutputStream out = Files.newOutputStream(scratch, CREATE_NEW, WRITE, DELETE_ON_CLOSE)) {
out.write(42);
}
System.out.println("scratch exists after close: " + Files.exists(scratch));
// clean up, deepest paths first
try (Stream<Path> paths = Files.walk(dir)) {
for (Path p : paths.sorted(Comparator.reverseOrder()).toList()) Files.delete(p);
}
System.out.println("cleaned up: " + Files.notExists(dir));
}
}
readString: first line|second line|third line|fourth line|
readAllLines: [first line, second line, third line, fourth line]
readAllBytes: 46 bytes
lines with 'th': 2
mismatch after copying content: -1
first differing byte: 18
CREATE_NEW on an existing file: FileAlreadyExistsException
header: id,name
raw bytes: [1, 2, 3]
reading Latin-1 as UTF-8: MalformedInputException
with the right charset: café
createDirectory without parents: NoSuchFileException
x/y/z is a directory: true
created a/empty.txt, size 0
createFile twice: FileAlreadyExistsException
temp file name pattern ok: true
scratch exists after close: false
cleaned up: true
The demo creates everything inside a temporary directory and deletes it all at the end, walking the tree in reverse order so that each directory is empty when it's deleted (article 28 explains Files.walk).
Common questions
How do I check whether a file exists?
Files.exists(path) and Files.notExists(path). Both can be false when the answer is unknown, for example without permission. But checking first and acting later has a race: the file may appear or disappear in between. Prefer simply attempting the operation and handling NoSuchFileException or FileAlreadyExistsException, or use options such as CREATE_NEW, which check and create atomically.
How large a file can readString or readAllBytes handle?
A Java array or string holds at most about 2 GB, so these methods fail with an OutOfMemoryError for larger files, and long before that if the heap is too small. Stream large files with Files.lines, a buffered reader, or a channel.
Can I insert text at the beginning of a file? No file system supports inserting bytes in front of existing ones. Write a new file with the new beginning followed by the old contents, then move it over the original.
Why does Files.write(path, lines) add a line break after the last line?
It writes a line separator after every line, including the last, which is the usual convention for text files on Unix. If you need exact control, join the lines yourself and use writeString.
On Windows, deleting or moving a file fails although my program "is done with it". Why?
A stream, reader or Files.lines stream is still open. Windows does not allow deleting open files. Close everything with try-with-resources. Note that a memory mapping (article 29) also keeps the file in use until it is garbage collected.
Where should my application store its data files?
Not in the working directory or the installation directory, which may be read-only. Use a subdirectory of System.getProperty("user.home"), or the platform's conventions (%APPDATA% on Windows, ~/Library/Application Support on macOS, $XDG_DATA_HOME on Linux), and create it with createDirectories.
API reference
java.nio.file.Files
| Method | Description |
|---|---|
static byte[] readAllBytes(Path path) | reads a whole file |
static String readString(Path path), readString(Path path, Charset cs) (Java 11) | reads a text file; malformed input throws |
static List<String> readAllLines(Path path), readAllLines(Path path, Charset cs) | reads all lines |
static Stream<String> lines(Path path), lines(Path path, Charset cs) | a lazy stream of lines; close it |
static Path write(Path path, byte[] bytes, OpenOption... options) | writes bytes |
static Path writeString(Path path, CharSequence csq, OpenOption... options), with a Charset (Java 11) | writes text |
static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options), with a Charset | writes lines |
static long mismatch(Path path, Path path2) (Java 12) | the first differing byte position, or -1 |
static String probeContentType(Path path) | a guess at the MIME type, or null |
static InputStream newInputStream(Path path, OpenOption... options), OutputStream newOutputStream(...) | byte streams for the file |
static BufferedReader newBufferedReader(Path path), BufferedWriter newBufferedWriter(Path path, OpenOption... options), with a Charset | buffered text access |
static Path createFile(Path path, FileAttribute<?>... attrs) | creates an empty file atomically; fails if it exists |
static Path createDirectory(Path dir, FileAttribute<?>... attrs), createDirectories(Path dir, FileAttribute<?>... attrs) | creates a directory, or a directory with any missing parents |
static Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs), createTempFile(Path dir, String prefix, String suffix, ...) | creates a temporary file |
static Path createTempDirectory(String prefix, ...), createTempDirectory(Path dir, String prefix, ...) | creates a temporary directory |
static Path createLink(Path link, Path existing), createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs) | create hard and symbolic links |
Summary
Files.readString,readAllLines,readAllBytesand the lazylinesread files. Text methods use UTF-8 by default and throw on malformed input.Files.writeString,writeand friends create or truncate by default. UseAPPEND,CREATE_NEWand otherStandardOpenOptions to change that, and remember that options replace the defaults.mismatchcompares files, andprobeContentTypeguesses MIME types.newInputStream,newOutputStream,newBufferedReaderandnewBufferedWritergive classic I/O objects for a path.createDirectoriesmakes sure a directory exists.createFilecreates atomically and fails if the file exists.- Temporary files and directories go in
java.io.tmpdirby default and must be deleted by you.
Practice Questions
Your log writer calls Files.writeString(log, line) for every line, but the file only ever contains the last line. Why, and what's the fix?
Without options, writeString truncates the file each time. Append instead: Files.writeString(log, line + "\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND). CREATE handles the very first write, when the file doesn't exist yet.
What's the difference between createDirectory and createDirectories when the directory already exists?
createDirectory throws FileAlreadyExistsException. createDirectories returns normally if the directory exists, so it's the right choice for "ensure this directory exists".
How can two processes safely agree that only one of them processes a job file?
Each tries Files.createFile(jobDir.resolve("job.claimed")). Creation is atomic and fails with FileAlreadyExistsException if the file exists, so exactly one process succeeds.
How do you check that two files have identical contents without reading both into memory?
Files.mismatch(a, b) == -1. It compares the files efficiently and returns the position of the first difference, or -1 if there is none.
Files.readAllLines(path) throws MalformedInputException, but the file opens fine in an editor. What's going on?
The file isn't valid UTF-8. It's probably in a legacy encoding such as Windows-1252 or ISO 8859-1. Pass the actual encoding, as in Files.readAllLines(path, Charset.forName("windows-1252")), or convert the file to UTF-8.
Previous: Java NIO Path: Creating, Resolving, Relativizing and Normalizing Paths
Next: Java Files: Copying, Moving, Deleting and Reading File Attributes
Related reading
- Java NIO Path: Creating, Resolving, Relativizing and Normalizing Paths
- Java ZIP Archives: ZipInputStream, ZipOutputStream and ZIP File Systems
- Java RandomAccessFile: Seeking and Fixed-Size Records
- Java DataInput and DataOutput: Reading and Writing Binary Data
- Java Character Encodings: UTF-8, Charsets and the Default Encoding

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.