Java Path Interface

Beginner
9 min read
Updated: Nov 2026
3 examples
java.nio.file.Path

Definition and Usage

In Java, java.nio.file.Path is an interface whose objects describe where a file or folder is, like an address on an envelope. It arrived in Java 7 with the "NIO.2" file API. A path is made of an optional root (such as / or C:\) and a list of name elements: /home/anna/notes.txt has the root / and the names home, anna, and notes.txt.

A Path is immutable and works only on names: getFileName(), getParent(), resolve(), normalize(), and relativize() never touch the disk, and the file does not need to exist. To create, read, or delete the file, hand the path to the Files class. The Path Methods index lists all 23 guides.

Outputs depend on the operating system.

Windows prints \ between names and needs a drive letter for an absolute path; macOS and Linux print /. Method pages show the Linux and macOS output and add a Windows note where the result really differs.

Java Syntax

Import Path and create it with Paths.get (Java 7+) or Path.of (Java 11+):

Java
import java.nio.file.Path;
import java.nio.file.Paths;

Path config = Paths.get("config", "app.properties"); // config/app.properties
Path same = Path.of("config/app.properties");        // Java 11+, equal to config
Path home = Paths.get("/home/anna");                 // absolute on Linux/macOS
Path file = home.resolve("todo.txt");                // /home/anna/todo.txt
String text = file.toString();                       // the path as a String

Illegal characters cause an unchecked InvalidPathException. On Linux and macOS only the NUL character is illegal; Windows also rejects characters such as < > : " | ? * inside a name.

Path vs File vs String

Three ways to hold a location, from oldest to newest:

TypeWhat it isUse it for
StringPlain text such as "docs/a.txt"Input and output only; joining strings by hand breaks on other systems
java.io.FileThe Java 1.0 file classOlder APIs; many methods just return false on failure
java.nio.file.PathRoot plus name elements (Java 7)New code, together with Files

Convert with path.toFile(), file.toPath(), path.toString(), and Paths.get(text).

Absolute and Relative Paths

An absolute path is complete on its own: /home/anna/todo.txt on Linux or C:\Users\anna\todo.txt on Windows. A relative path such as docs/todo.txt is read from the program's working directory. isAbsolute() tells them apart, getRoot() returns the root (or null), and toAbsolutePath() turns a relative path into an absolute one. Name elements are numbered from 0 without the root: getNameCount(), getName(), subpath(), and iterator() work with them.

Separators on Each System

SystemSeparatorAbsolute exampleCase-sensitive equals
Linux//home/anna/a.txtYes
macOS//Users/anna/a.txtYes (comparison of the text)
Windows\ (also accepts /)C:\Users\anna\a.txtNo

Ask the running system with getFileSystem().getSeparator() instead of hard-coding a separator.

Path Works Together with Files

Build the location with Path methods, then pass it to a Files method: Files.exists, Files.createDirectories, Files.readAllLines, Files.write, or Files.walk. When you join user input onto a base folder, call normalize() and then startsWith() to make sure "../" did not escape the folder.

Java Examples

Example 1 — Take a Report Path Apart

Print the root, the parent folder, the file name, and every name element of one absolute path. No file has to exist.

Java
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathHubAnatomy {
    public static void main(String[] args) {
        Path report = Paths.get("/home/anna/reports/2026/summary.pdf");
        System.out.println("Root:     " + report.getRoot());
        System.out.println("Parent:   " + report.getParent());
        System.out.println("File:     " + report.getFileName());
        System.out.println("Absolute: " + report.isAbsolute());
        int i = 0;
        for (Path part : report) {
            System.out.println("  name " + i + " = " + part);
            i++;
        }
    }
}

How It Works

  1. Only a name. Paths.get parses the text into a root and five name elements; Java does not check whether /home/anna exists.
  2. Three quick questions. getRoot(), getParent(), and getFileName() each return a new Path, and string concatenation prints it with toString().
  3. A Path is Iterable. The for-each loop visits the name elements from the root side outward; the root itself is not one of them, so index 0 is home.

Example 2 — Build a Log Path from Parts and Clean It

Join a project folder with sub-folders and a file name, then remove a .. step and compute a relative path back to the project.

Java
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathHubCombine {
    public static void main(String[] args) {
        Path project = Paths.get("projects", "shop");
        Path log = project.resolve("build/../logs").resolve("server.log");
        System.out.println("Joined:     " + log);
        Path clean = log.normalize();
        System.out.println("Normalized: " + clean);
        System.out.println("Relative:   " + project.relativize(clean));
        System.out.println("Inside:     " + clean.startsWith(project));
    }
}

How It Works

  1. resolve only glues. Each resolve call appends names with the separator and keeps build/.. exactly as written.
  2. normalize does the cleanup. It drops build together with the .. that follows it, which leaves projects/shop/logs/server.log.
  3. Back to the project. relativize strips the shared projects/shop prefix, and startsWith confirms the cleaned path is still inside the project folder.

Example 3 — Compare String Joining, Path, and File

Glue a folder and a file name together as plain text, as a Path, and as a File, and see which one cleans up a doubled slash.

Java
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathHubThreeForms {
    public static void main(String[] args) {
        String folder = "reports/";
        String text = folder + "/" + "jan.txt";
        Path p1 = Paths.get(text);
        Path p2 = Paths.get("reports").resolve("jan.txt");
        Path p3 = Paths.get("reports", "jan.txt");
        File f = p3.toFile();
        System.out.println("String concat: " + text);
        System.out.println("as Path:       " + p1);
        System.out.println("all equal:     " + (p1.equals(p2) && p2.equals(p3)));
        System.out.println("as File:       " + f.getName() + " in " + f.getParent());
        System.out.println("length:        " + p3.toString().length() + " characters");
    }
}

How It Works

  1. Text keeps every mistake. String concatenation produces reports//jan.txt with a doubled slash, because a String knows nothing about paths.
  2. Path parses and cleans. Paths.get(text) collapses the repeated separator, so all three ways of building the path give equal Path objects.
  3. File for older code. toFile() gives the same location as a java.io.File; its getters return Strings, and the clean path text is 15 characters long.

Next: Java Path Methods by Group

Full list with short descriptions: Java Path Methods index.

Frequently Asked Questions

An interface, added in Java 7 as part of NIO.2, whose objects describe the location of a file or folder as a root plus a list of names. A Path is immutable and does not need to exist on disk.
Use Path with the Files class for new code. It reports errors with clear exceptions and supports links, attributes, and other file systems. Convert with path.toFile() and file.toPath() when an older API needs a File.
They create the same kind of Path. Paths.get works on Java 7 and later; Path.of was added in Java 11 and is the recommended style there. The examples on this site use Paths.get so they run on Java 8.
Each operating system has its own separator. Windows uses a backslash and macOS and Linux use a slash. Java accepts forward slashes in Paths.get on Windows too, but toString always prints the native separator.
No. Paths.get and Path.of only parse text. Use Files.createFile, Files.createDirectories, or Files.write to make something on disk, and Files.exists to check it.

Browse every Path method

Open the methods index for categorized guides with runnable examples and FAQs.

Path Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful