Java Files
Programs often need to save data that outlives a single run: settings, logs, reports, exported CSV files. Modern Java handles files through the NIO.2 API in java.nio.file, built around two types:
Path— a location in the file system, likereports/2026/q3.csv.Files— a class of static methods that create, read, write, copy and delete files.
Note: The examples on this page create temporary files, so they run safely in the playground and leave nothing behind. In your own programs you would usually use a fixed path such as
Path.of("data.txt").
Paths
import java.nio.file.Path;
class Main {
public static void main(String[] args) {
Path p = Path.of("reports", "2026", "summary.txt");
System.out.println(p);
System.out.println("File name: " + p.getFileName());
System.out.println("Parent: " + p.getParent());
System.out.println("Parts: " + p.getNameCount());
System.out.println("Sibling: " + p.resolveSibling("details.txt"));
System.out.println("Absolute? " + p.isAbsolute());
}
}reports/2026/summary.txt
File name: summary.txt
Parent: reports/2026
Parts: 3
Sibling: reports/2026/details.txt
Absolute? false
Creating a Path doesn't touch the disk — it's only a description of a location. (On Windows the separator would be \ instead of /.)
Writing and reading text
For small files, Files can write or read the whole content in a single call. All text methods use UTF-8 by default.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
class Main {
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("notes", ".txt");
Files.writeString(file, "Buy milk\nCall Sam\n");
System.out.println("Size: " + Files.size(file) + " bytes");
String all = Files.readString(file);
System.out.print(all);
Files.write(file, List.of("Line A", "Line B", "Line C")); // overwrite with lines
List<String> lines = Files.readAllLines(file);
System.out.println(lines.size() + " lines, last = " + lines.get(lines.size() - 1));
Files.delete(file);
System.out.println("Exists after delete: " + Files.exists(file));
}
}Size: 18 bytes
Buy milk
Call Sam
3 lines, last = Line C
Exists after delete: false
Most file methods throw the checked IOException, so you must catch it or declare throws IOException.
| Method | Does |
|---|---|
Files.writeString(path, text) |
write a string (creates or replaces the file) |
Files.write(path, lines) |
write a list of lines |
Files.readString(path) |
read the whole file as one string |
Files.readAllLines(path) |
read into a List<String> |
Files.lines(path) |
a lazy Stream<String> — good for large files |
Files.exists(path) / Files.size(path) |
check existence / get size |
Files.copy(a, b) / Files.move(a, b) |
copy / move or rename |
Files.delete(path) / Files.deleteIfExists(path) |
remove |
Files.createDirectories(path) |
create a folder (and missing parents) |
Appending
Pass StandardOpenOption.APPEND to add to the end of a file instead of replacing it — typical for log files:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
class Main {
public static void main(String[] args) throws IOException {
Path log = Files.createTempFile("app", ".log");
Files.writeString(log, "started\n");
Files.writeString(log, "user logged in\n", StandardOpenOption.APPEND);
Files.writeString(log, "stopped\n", StandardOpenOption.APPEND);
System.out.print(Files.readString(log));
Files.deleteIfExists(log);
}
}started
user logged in
stopped
Processing a CSV file line by line
Files.lines returns a stream, so you can combine file reading with everything from the Streams chapter. Close it with try-with-resources:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
class Main {
public static void main(String[] args) throws IOException {
Path csv = Files.createTempFile("sales", ".csv");
Files.writeString(csv, """
product,qty,price
pen,10,1.50
notebook,4,3.25
bag,1,24.00
""");
try (Stream<String> lines = Files.lines(csv)) {
double total = lines
.skip(1) // header
.map(line -> line.split(","))
.mapToDouble(cols -> Integer.parseInt(cols[1]) * Double.parseDouble(cols[2]))
.sum();
System.out.printf("Total sales: %.2f%n", total);
}
Files.delete(csv);
}
}Total sales: 52.00
Directories
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
class Main {
public static void main(String[] args) throws IOException {
Path root = Files.createTempDirectory("project");
Path src = Files.createDirectories(root.resolve("src/main"));
Files.writeString(src.resolve("App.java"), "class App {}");
Files.writeString(src.resolve("Util.java"), "class Util {}");
Files.writeString(root.resolve("README.md"), "# Project");
try (Stream<Path> all = Files.walk(root)) {
all.filter(Files::isRegularFile)
.map(p -> root.relativize(p).toString())
.sorted()
.forEach(System.out::println);
}
try (Stream<Path> walk = Files.walk(root)) { // clean up: deepest paths first
walk.sorted((a, b) -> b.getNameCount() - a.getNameCount())
.forEach(p -> p.toFile().delete());
}
System.out.println("Cleaned up: " + !Files.exists(root));
}
}README.md
src/main/App.java
src/main/Util.java
Cleaned up: true
Handling missing files
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
class Main {
public static void main(String[] args) {
Path missing = Path.of("does-not-exist.txt");
try {
Files.readString(missing);
} catch (NoSuchFileException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("Other I/O problem: " + e.getMessage());
}
}
}File not found: does-not-exist.txt
Tip: You'll still see the older
java.io.File,FileReaderandBufferedWriterclasses in existing code. They work, butPathandFilesare simpler and give better error messages — prefer them in new code.
Test yourself
Which method reads an entire small text file into one String?
- Files.read(path)
- Files.readString(path)
- Path.read()
- new File(path).text()
What does Files.writeString(path, text) do if the file already exists?
- Appends the text
- Throws an exception
- Replaces the content
- Does nothing
Why should a stream from Files.lines be used in try-with-resources?
- It's faster
- It keeps the file open until the stream is closed
- It's required for UTF-8
- To catch NumberFormatException