Skip to content
Tutorials Center
My learning

Topics

Lesson 113 of 201 ยท Input and Output

Reading and Writing Files

Read and write files in Java with Path and Files - writeString, readString, readAllLines, lines, append, copy, move, delete - plus error handling and safe, atomic writes.

Sooner or later every program needs to keep data after it exits: settings, a log, a report, an exported CSV, a cache. Files are the simplest place to put it. Modern Java does almost all file work with two types from the java.nio.file package: Path, which describes where a file is, and Files, a class full of static methods that do things with files: read, write, copy, move, delete and inspect.

This lesson shows the one-line methods that cover most everyday needs, how to read large files without running out of memory, how appending and other open options work, which exceptions to expect, and the professional habit of writing a file atomically so a crash never leaves it half-written. The examples write real files on our server. Each run gets a fresh, empty working folder, so files you create exist only until that run ends.

Paths: naming a file

A Path is just a name: a sequence of folder names ending in a file or folder name. Creating a Path doesn't touch the disk, and the file doesn't need to exist:

Java Building and taking apart paths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

  • Path.of(first, more...) (Java 11) creates a path; it joins parts with the operating system's separator (/ on Linux and macOS, \ on Windows). Older code uses Paths.get(...), which does the same thing.
  • A relative path like reports/2025/october.csv is resolved against the program's working directory. An absolute path starts at the root (/home/maya/... or C:\Users\...).
  • resolve appends a path; resolveSibling replaces the last part; normalize removes . and name/.. pairs; relativize computes the path from one location to another.
  • Path has no method that returns the file extension (as of Java 25), so take it from getFileName().toString() as shown.
  • Avoid building paths by concatenating strings with "/". resolve handles separators for you and works on every OS.

Writing and reading a whole file

For small and medium files (configuration, reports, anything that fits comfortably in memory), Files has one-line methods:

Java writeString, readString, write and readAllLines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The four methods in this example are the ones you'll use most:

Method What it does
Files.writeString(path, text) Writes a String, creating the file or replacing its content
Files.readString(path) Reads the whole file into one String
Files.write(path, lines) Writes each element of an Iterable as a line
Files.readAllLines(path) Reads the file into a List<String>, one element per line, without line separators
Files.write(path, bytes) / Files.readAllBytes(path) The same for raw byte[] data, like images

All the text methods use UTF-8 unless you pass a Charset as an extra argument, regardless of the platform. That's different from some older java.io classes, and it's why the Character Sets and Encoding lesson matters. readAllLines recognizes \n, \r\n and \r line endings, so it reads files from any OS.

Each of these methods opens the file, does its work and closes it, even if an error occurs. You never need close() for them.

Appending and open options

By default, writing replaces the file. Pass StandardOpenOption values to change that:

Java Appending to a log with open options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The most useful options:

  • CREATE: create the file if it doesn't exist. CREATE_NEW: create it, and fail with FileAlreadyExistsException if it exists, which is a safe way to claim a file name.
  • APPEND: write at the end instead of replacing.
  • TRUNCATE_EXISTING: empty the file before writing. With no options at all, the write methods behave as if you passed CREATE, TRUNCATE_EXISTING and WRITE.
  • WRITE and READ: the access mode, used with lower-level channels and streams.

Opening a file for every line, as log does here, is fine for a few writes. For many lines, keep one writer open, as shown in Byte and Character Streams.

Large files: reading line by line

readString and readAllLines load the entire file into memory. For a 5 GB server log, that's a crash waiting to happen. Files.lines(path) returns a lazy Stream<String> that reads one line at a time, so memory use stays small no matter how big the file is:

Java Processing a big file lazily with Files.lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Always close Files.lines. Unlike readAllLines, the stream keeps the file open until it's closed, so use it in a try-with-resources block, as above. Forgetting this leaks file handles; on Windows it also prevents the file from being deleted or renamed. The same rule applies to Files.list, Files.walk and Files.find from Working with Directories.

The stream is lazy: findFirst reads just one line and stops. You can combine Files.lines with every operation from Streams. For line-by-line processing with a classic loop, or for writing large files, use Files.newBufferedReader and Files.newBufferedWriter, covered in the next lesson.

Checking, copying, moving and deleting

Files also manages files as a whole:

Java exists, copy, move, delete and mismatch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What to know:

  • exists / notExists, isRegularFile, isDirectory, isReadable, isWritable and size inspect a path. Checking exists right before an operation is often pointless: another program could delete the file in between. It's usually better to just try the operation and handle the exception.
  • createDirectory creates one folder and fails if the parent is missing; createDirectories creates every missing folder in the path and doesn't complain if it already exists.
  • copy and move fail if the target exists, unless you pass StandardCopyOption.REPLACE_EXISTING. move within the same disk is a fast rename.
  • delete throws NoSuchFileException for a missing file; deleteIfExists returns false instead. Folders can only be deleted when empty; deleting a whole tree is shown in Working with Directories.
  • Files.mismatch(a, b) (Java 12) returns -1 if two files have identical content, or the position of the first difference.

Handling errors

Almost every Files method throws the checked IOException, because the disk, the network share or the permissions can fail at any moment. Specific subclasses tell you what went wrong:

Exception Typical cause
NoSuchFileException The file or one of its parent folders doesn't exist
FileAlreadyExistsException CREATE_NEW, copy, move or createDirectory hit an existing target
AccessDeniedException No permission, or the file is locked by another program
DirectoryNotEmptyException Deleting a folder that still contains files
NotDirectoryException Listing something that's a file, not a folder
MalformedInputException Reading text whose bytes aren't valid in the charset (UTF-8 by default)

In small programs, declaring throws IOException on main is fine. In real applications, catch the exception where you can do something useful: show a clear message, fall back to defaults, or wrap it in your own exception (Custom Exceptions). Never swallow it silently.

Writing a file safely

If the program crashes or the power fails halfway through writeString, the file is left half-written: the old content is gone and the new content is incomplete. For important files like settings or saved games, professionals write to a temporary file first and then move it over the real one. On local disks the move can be atomic: other programs see either the complete old file or the complete new file, never a mix.

Java An atomic save with a temporary file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The temporary file is created in the same folder as the target because an atomic move only works within one file system. createTempFile picks a unique name, so two processes saving at the same time don't overwrite each other's temporary files. The finally block removes the temporary file if writing failed; after a successful move it's already gone, so deleteIfExists simply returns false.

The legacy java.io.File class

Code written before Java 7 uses java.io.File instead of Path. You'll still meet it in older libraries and in APIs like ProcessBuilder.directory(File). It has real design problems: methods like delete() and mkdir() return false on failure without saying why, and listFiles() returns null instead of throwing. Prefer Path and Files, and convert at the boundaries:

Java
File legacy = new File("report.csv");
Path modern = legacy.toPath();     // File -> Path
File back = modern.toFile();       // Path -> File

Working with Directories compares the two in more detail.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A file todo.txt contains three lines. What happens after Files.writeString(Path.of("todo.txt"), "walk dog\n")?

    Without options, writeString creates or truncates the file, so the old content is replaced. Use CREATE and APPEND to add to the end.
  2. 2. You need to count lines containing "ERROR" in a 10 GB log. Which approach is right?

    Files.lines reads lazily, one line at a time, so memory stays small. The other options load the whole file into memory. The stream must be closed, hence try-with-resources.
  3. 3. What does Path.of("docs/./guide/../intro.md").normalize() return?

    normalize removes the "." element and the "guide/.." pair, leaving docs/intro.md. It works purely on the name and doesn't touch the disk.
  4. 4. Files.copy(a, b) fails with FileAlreadyExistsException. How do you overwrite b?

    copy and move refuse to replace an existing target unless you pass REPLACE_EXISTING.
  5. 5. Why write to a temporary file and then move it over the target?

    If the program dies while writing, only the temporary file is damaged. The move then replaces the target in one step, atomically on most local file systems.

Summary

  • Path.of(...) names a file or folder without touching the disk; combine paths with resolve, clean them with normalize.
  • Files.writeString/readString, Files.write/readAllLines and readAllBytes handle whole files in one call, using UTF-8 by default and closing the file for you.
  • Writing replaces content by default; pass CREATE and APPEND to append, or CREATE_NEW to refuse existing files.
  • Files.lines streams huge files line by line; always close it with try-with-resources.
  • createDirectories, copy, move, delete/deleteIfExists, exists, size and mismatch manage files; copy and move need REPLACE_EXISTING to overwrite.
  • File operations throw IOException subclasses that describe the problem; for important files, write a temp file and move it into place atomically.

Next: Byte and Character Streams, where you'll learn the streams, readers and writers underneath Files, and how to work with data that doesn't come from a file at all.