Java Path toRealPath() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 7+

Definition

In Java, path.toRealPath() asks the file system for the real location of an existing file or folder. The result is absolute, contains no . or .., follows symbolic links to their targets, and on case-insensitive systems may use the real letter case of the names.

Unlike most Path methods, it reads the disk, so the file must exist; otherwise it throws NoSuchFileException. It is the NIO.2 counterpart of File.getCanonicalPath().

An instance method of the java.nio.file.Path interface, available since Java 7. Call it on a Path object, as in path.toRealPath(...), after import java.nio.file.Path;.

Syntax

It declares throws IOException; pass LinkOption.NOFOLLOW_LINKS to keep links unresolved:

Java
Path real = path.toRealPath();                           // follows links
Path noLinks = path.toRealPath(LinkOption.NOFOLLOW_LINKS); // keeps links
CallWhat it does
p.toRealPath()Absolute, cleaned, links followed; the file must exist.
p.toRealPath(LinkOption.NOFOLLOW_LINKS)Same, but symbolic links are not replaced by their targets.
a.toRealPath().equals(b.toRealPath())Do two spellings lead to the same file?

Since Java 7. Each example creates its own files in a fresh Files.createTempDirectory folder, prints only names and booleans, and deletes everything at the end.

Library declarations
Java
// java.nio.file.Path (interface)
Path toRealPath(LinkOption... options) throws IOException

Parameters

ParameterDescription
optionsOptional LinkOption.NOFOLLOW_LINKS; without it, symbolic links are followed.

Return Value

Return ValueDescription
PathThe absolute real path of the existing file.

Compare with Similar Methods

How the three "make it complete" methods differ:

MethodHow it differs
toAbsolutePath()Adds the working directory only; no disk access, keeps ...
normalize()Removes . and .. from the text; ignores links.
Files.isSameFile()Answers "same file?" directly, without returning a path.

Java Examples

Outputs below are shown for Linux and macOS. On Windows, Java prints \ between names instead of /; the note above each output says when a result really differs.

Example 1 — Resolve a Path with ".." to the Real File

Create a file and a sub-folder in a temp folder, then ask for the real path of a spelling that goes through the sub-folder and back.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class PathToRealPathClean {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path sub = Files.createDirectory(dir.resolve("sub"));
        Path file = Files.createFile(dir.resolve("data.txt"));
        Path real = dir.resolve("sub/../data.txt").toRealPath();
        System.out.println("file name:      " + real.getFileName());
        System.out.println("absolute:       " + real.isAbsolute());
        System.out.println("already normal: " + real.normalize().equals(real));
        System.out.println("same as file:   " + real.equals(file.toRealPath()));
        Files.delete(file);
        Files.delete(sub);
        Files.delete(dir);
    }
}

How It Works

  1. Every step must exist. The detour sub/.. only works because sub was created first; the operating system walks the real folders, so a missing sub would cause NoSuchFileException.
  2. A clean, absolute answer. The real path ends in data.txt, is absolute, and has no . or .. left, which is why normalizing it changes nothing.
  3. Compare real with real. The check uses file.toRealPath(), not file: on macOS the temp folder is reached through a link, so only the two real paths are guaranteed to match.

Example 2 — Handle NoSuchFileException for a Missing File

Ask for the real path of a file that does not exist yet, then create it and ask again. toAbsolutePath() works in both cases.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;

public class PathToRealPathMissing {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path report = dir.resolve("report.txt");
        System.out.println("exists: " + Files.exists(report));
        System.out.println("toAbsolutePath works: " + report.toAbsolutePath().isAbsolute());
        try {
            report.toRealPath();
        } catch (NoSuchFileException e) {
            System.out.println("toRealPath -> " + e.getClass().getSimpleName());
        }
        Files.createFile(report);
        System.out.println("after createFile: " + report.toRealPath().getFileName());
        Files.delete(report);
        Files.delete(dir);
    }
}

How It Works

  1. Text-only methods do not care. report.txt does not exist yet, but toAbsolutePath() still returns an absolute path, because it never asks the disk.
  2. toRealPath does care. Asking for the real location of a missing file throws NoSuchFileException; the program prints only the class name, since the message contains the temp path.
  3. Create, then it works. After Files.createFile the same call succeeds, and the real path ends with report.txt.

Example 3 — Remove Duplicate Paths That Point to the Same File

Four spellings point to only two files. A TreeSet of the typed paths keeps all four; a set of real paths keeps two.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Set;
import java.util.TreeSet;

public class PathToRealPathDedupe {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path logs = Files.createDirectory(dir.resolve("logs"));
        Path a = Files.createFile(dir.resolve("a.txt"));
        Path b = Files.createFile(dir.resolve("b.txt"));
        Path[] given = {a, dir.resolve("./a.txt"), logs.resolve("../a.txt"), b};
        Set<Path> typed = new TreeSet<>();
        Set<Path> real = new TreeSet<>();
        for (Path p : given) {
            typed.add(p);
            real.add(p.toRealPath());
        }
        System.out.println("paths given:         " + given.length);
        System.out.println("distinct as typed:   " + typed.size());
        System.out.println("distinct real files: " + real.size());
        for (Path r : real) {
            System.out.println("  " + r.getFileName());
        }
        Files.delete(a);
        Files.delete(b);
        Files.delete(logs);
        Files.delete(dir);
    }
}

How It Works

  1. Different text, same file. a.txt, ./a.txt, and logs/../a.txt are three spellings of one file, so the TreeSet of typed paths, which compares text, still holds four entries.
  2. Real paths collapse duplicates. toRealPath() turns all three spellings into the same absolute path, so the second set ends up with just a.txt and b.txt.
  3. Sorted, short output. A TreeSet orders paths with compareTo, and printing only getFileName() keeps the random temp folder out of the output.

Frequently Asked Questions

It asks the file system for the real location of an existing file: an absolute path with "." and ".." resolved and symbolic links followed.
The file or one of the folders on the way does not exist. toRealPath needs a real file; use toAbsolutePath or normalize for paths that may not exist.
normalize only edits the text and never fails. toRealPath reads the disk, follows links, and fails for missing files.
Pass LinkOption.NOFOLLOW_LINKS: path.toRealPath(LinkOption.NOFOLLOW_LINKS).
They serve the same purpose. toRealPath returns a Path and throws specific exceptions such as NoSuchFileException, while getCanonicalPath returns a String and works for missing files too.

Next: Path.toString()

Get the path as text, using the separator of the operating system.

toString() tutorial →

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