NIO.2 Path and Files Classes

Naveen AnamaneniUpdated · 5 min read

NIO.2 is the modern file API in Java, in the java.nio.file package, added in Java 7. It has two central types. Path is an interface that represents a location in the file system, such as school/2026/marks.txt; it doesn't open or touch the file. Files is a utility class of static methods that do the actual work: create, read, write, copy, move, delete and inspect files. In this lesson, you will learn how to build and work with paths, and the most important methods of Files.

Creating a Path

WayExample
From partsPath.of("school", "2026", "marks.txt")
From one stringPath.of("school/2026/marks.txt")
From a Filefile.toPath()
Relative to another pathdir.resolve("marks.txt")

Paths.get(...) is an older equivalent of Path.of(...).

A path is a sequence of names; Path methods work on those names

Methods of Path

MethodDescription
getFileName()It is used to get the last part, such as marks.txt.
getParent()It returns the path without the last part.
getRoot()It returns the root (/ or C:\), or null for relative paths.
getNameCount(), getName(i)It counts and returns the parts.
resolve(other)It joins a child path onto this one.
resolveSibling(name)It replaces the last part.
relativize(other)It returns the path from this one to another.
normalize()It removes . and .. parts.
toAbsolutePath()It turns a relative path into a full one.
startsWith, endsWithIt compares path parts.

Example: Working with Paths

Let's see an example of path operations. None of these files need to exist.

PathDemo.java▶ Try it
import java.nio.file.Path;
 
public class PathDemo {
    public static void main(String[] args) {
        Path marks = Path.of("school", "2026", "marks.txt");
 
        System.out.println("Path:      " + marks);
        System.out.println("File name: " + marks.getFileName());
        System.out.println("Parent:    " + marks.getParent());
        System.out.println("Parts:     " + marks.getNameCount());
        System.out.println("Absolute?  " + marks.isAbsolute());
 
        Path report = marks.resolveSibling("report.pdf");
        System.out.println("Sibling:   " + report);
 
        Path messy = Path.of("school/2026/../2025/./notes.txt");
        System.out.println("Normalized: " + messy.normalize());
 
        Path base = Path.of("school");
        System.out.println("Relative:  " + base.relativize(marks));
        System.out.println("Ends with marks.txt? "
            + marks.endsWith("marks.txt"));
    }
}
Output
Path:      school/2026/marks.txt
File name: marks.txt
Parent:    school/2026
Parts:     3
Absolute?  false
Sibling:   school/2026/report.pdf
Normalized: school/2025/notes.txt
Relative:  2026/marks.txt
Ends with marks.txt? true

Explanation: Path.of joins the parts with the correct separator (/ on macOS and Linux, \ on Windows). resolveSibling swaps the file name. normalize removes .. (which cancels 2026) and .. relativize gives the path from school to the file.

Methods of Files

GroupMethods
Checkexists, notExists, isRegularFile, isDirectory, isReadable, isWritable, size
CreatecreateFile, createDirectory, createDirectories, createTempFile
ReadreadString, readAllLines, readAllBytes, lines, newBufferedReader, newInputStream
WritewriteString, write, newBufferedWriter, newOutputStream
Managecopy, move, delete, deleteIfExists
Folderslist, walk, find, newDirectoryStream
AttributesgetLastModifiedTime, setLastModifiedTime, getOwner, readAttributes

Example: Inspecting a File

Inspect.java▶ Try it
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
 
public class Inspect {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("diary.txt");
        Files.writeString(file, "Dear diary, today Advitha learned NIO.2.");
 
        System.out.println("Regular file? " + Files.isRegularFile(file));
        System.out.println("Directory?    " + Files.isDirectory(file));
        System.out.println("Readable?     " + Files.isReadable(file));
        System.out.println("Size:         " + Files.size(file) + " bytes");
        System.out.println("Exists other? "
            + Files.exists(Path.of("nope.txt")));
    }
}
Output
Regular file? true
Directory?    false
Readable?     true
Size:         40 bytes
Exists other? false

Explanation: Files.writeString creates the file with the text. The is... methods check what kind of entry it is and what the program may do with it, and size returns its length in bytes.

Common Mistakes

Expecting Path.of("a.txt") to create a file. Use Files.createFile or a write method.

Forgetting normalize() before comparing paths. a/../b and b are different Path objects until normalized.

Using string concatenation for paths. Use resolve.

Interview Corner

What are the Path and Files classes in Java?

Path (in java.nio.file) is an interface representing a hierarchical file system location, created with Path.of(...); it supports operations on the path itself such as resolve, relativize, normalize and getParent, without accessing the file system. Files is a utility class of static methods that operate on the file system using paths: checking, creating, reading, writing, copying, moving, deleting, listing and walking files and directories, and reading attributes. Together they form the NIO.2 API introduced in Java 7.

Practice

  1. Easy: Build the path reports/2026/november.csv and print its file name, parent and number of parts.
  2. Harder: Write a method that changes a file's extension, such as marks.txt to marks.csv, using resolveSibling and string methods.

Quick check: Path and Files

4 questions
1Does Path.of("a.txt") create a file?
2What does normalize() remove?
3Which method joins a child onto a path?
4What kind of methods does the Files class have?

Key Takeaways

Was this tutorial helpful?

Lesson 354 of 482