Java Files and Directories with NIO.2: Path and Files
Path.of("invoices", "2026", "inv-101.pdf") is only an address: getFileName, getParent and resolve work, but nothing is on disk. Files.createDirectories and createFile make an order file and delete removes it, Files.walk finds 4 .java files, and os.name tells Windows from Linux.
What you will learn
- Build an operating-system-independent path with Path.of and read its parts
- Create and delete folders and files with the Files class
- List every file below a folder with Files.walk
- Find the operating system and its path separator
Before you start
- Java try-with-resources and clean error handling
- Java streams I: filter, map and reduce
Programs often have to deal with files, and to reach a file you first need its path. NIO.2 (the java.nio.file package) gives you two tools: Path, an address, and Files, which does the work on disk. The outputs below come from a Windows machine, so they show backslashes; on macOS or Linux you'll see forward slashes.
A path is only an address
package org.studyeasy.s07l01;
import java.nio.file.Files;
import java.nio.file.Path;
public class Ex01_PathParts {
public static void main(String[] args) {
// A Path is only an address, nothing is created
Path invoice = Path.of("invoices", "2026", "inv-101.pdf");
System.out.println("Path: " + invoice);
System.out.println("File name: " + invoice.getFileName());
System.out.println("Parent: " + invoice.getParent());
System.out.println("Parts: " + invoice.getNameCount());
// resolve: add one more name to the end of a path
Path receipt = invoice.getParent().resolve("rcpt-101.pdf");
System.out.println("Receipt: " + receipt);
System.out.println("On disk? " + Files.exists(receipt));
}
}
Path: invoices\2026\inv-101.pdf
File name: inv-101.pdf
Parent: invoices\2026
Parts: 3
Receipt: invoices\2026\rcpt-101.pdf
On disk? false
The separator differs between Windows, Linux and macOS, so you give Path.of the names and Java joins them correctly. This is a relative path: the invoices folder sits next to where the program runs. getFileName gives the last part, getParent everything before it, and getNameCount counts the parts. resolve adds a name to the end. A Path never creates anything, so Files.exists is false.
Make a folder and a file, then remove it
Path folder = Path.of("orders", "2026");
Path order = folder.resolve("order-1042.txt");
// creates the folder and any missing parent folders
Files.createDirectories(folder);
System.out.println("Folder exists: " + Files.exists(folder));
// creates an empty file; its folder must exist
Files.createFile(order);
System.out.println("Created: " + order);
System.out.println("File exists: " + Files.exists(order));
Files.delete(order);
// the file is already gone: no error here
Files.deleteIfExists(order);
System.out.println("After delete: " + Files.exists(order));
Folder exists: true
Created: orders\2026\order-1042.txt
File exists: true
After delete: false
createDirectories makes orders and the 2026 folder inside it, and doesn't complain if they already exist. createFile makes an empty file. delete removes it, and deleteIfExists does nothing if it's already gone. These methods throw the checked IOException, so main declares throws.
| When something is off | Result |
|---|---|
createDirectories, folder already there | no error |
createFile, file already exists | FileAlreadyExistsException |
createFile, folder missing | NoSuchFileException |
a second delete | NoSuchFileException |
Every file below a folder
// walk: every folder and file below src
try (Stream<Path> tree = Files.walk(Path.of("src"))) {
List<Path> javaFiles = tree
.filter(p -> p.toString().endsWith(".java"))
.sorted().toList();
for (Path file : javaFiles) {
System.out.println(file.getFileName() + " -> " + file);
}
System.out.println("Java files: " + javaFiles.size());
}
Ex01_PathParts.java -> src\main\java\org\studyeasy\s07l01\Ex01_PathParts.java
Ex02_CreateDelete.java -> src\main\java\org\studyeasy\s07l01\Ex02_CreateDelete.java
Ex03_WalkFolder.java -> src\main\java\org\studyeasy\s07l01\Ex03_WalkFolder.java
Ex04_OsCheck.java -> src\main\java\org\studyeasy\s07l01\Ex04_OsCheck.java
Java files: 4
When you know a parent folder but not what's inside, Files.walk returns a stream of every folder and file below it, here ten paths: six folders and four files. The filter keeps the four ending in .java. The stream holds the folder open, so it goes in try-with-resources to be closed. A folder that doesn't exist gives NoSuchFileException.
Which system, which separator
// os.name is "Windows 11", "Mac OS X", "Linux" ...
String os = System.getProperty("os.name");
boolean windows = os.toLowerCase().contains("win");
// backslash on Windows, forward slash on macOS and Linux
String sep = FileSystems.getDefault().getSeparator();
// Path.of picks the separator, so no gluing by hand
Path report = Path.of("reports", "2026", "march.csv");
OS: Windows 11
Windows? true
Separator: \
Report: reports\2026\march.csv
The OS and separator lines will differ on your machine. You rarely need the separator yourself, because Path.of picks it for you.
Recap
| Call | What it does |
|---|---|
Path.of("a", "b", "c.txt") | an address; nothing on disk |
getFileName, getParent, resolve | read or extend the path |
Files.createDirectories, createFile | make folders and files |
Files.delete, deleteIfExists | remove a file |
Files.walk | every path below a folder |
A Path is only an address; Files does the work. Next: putting text in those files, in reading and writing text files.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Reading and Writing Text Files in Java
Files.readString reads tasks.txt in one call and readAllLines splits it into three tasks. writeString makes a shopping list that Files.lines filters to 2 items starting with B, a BufferedWriter writes an invoice, a Scanner totals 257, and Café is 4 characters but 5 bytes.
Java Structured Data: Reading and Writing JSON and CSV
Two Student records, Emma Clark with 91 in Java and Liam Brown with 78 in SQL, saved two ways. Jackson's ObjectMapper writes them to students.json and reads them back in one call each; plain Java writes students.csv with a header and reads it back by splitting at the commas.
