Java File Paths

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 139 of 306

What a Path Is

A path identifies the location of a file or folder in a file system. It is a sequence of names separated by a separator character, optionally starting from a root:

/home/asha/app/reports/2026/sales.csv
│ └──┬─┘ └┬┘ └──┬──┘ └┬─┘ └───┬───┘
root name  name  name  name   file name

In Java, a path is represented by the interface java.nio.file.Path. A Path object is just a structured description of a location — creating or manipulating one never touches the disk. The file it describes may or may not exist. Operations that need the actual file (reading, checking existence, resolving links) are done through Files or a few specific Path methods such as toRealPath.

This separation is useful: you can build, combine and validate paths freely, and only when you perform an I/O operation does the file system get involved.

Creating Path Objects

Path a = Path.of("/home/asha/app/config.yaml");      // one string
Path b = Path.of("reports", "2026", "sales.csv");     // several parts joined with the separator
Path c = Paths.get("reports", "2026", "sales.csv");   // older equivalent (Java 7)
Path d = new java.io.File("notes.txt").toPath();      // from a java.io.File
  • Path.of (Java 11+) is the standard way. Passing parts separately lets Java insert the right separator for the operating system, so Path.of("reports", "2026", "sales.csv") becomes reports/2026/sales.csv on Linux and reports\2026\sales.csv on Windows.
  • Paths.get does exactly the same thing and is still common in code written for Java 7–10. Path.of(...).equals(Paths.get(...)) is true.
  • An invalid path string — for example one containing a character the operating system forbids, such as : in a Windows file name or a NUL character — throws InvalidPathException (unchecked) immediately.

Inspecting the Parts of a Path

import java.nio.file.*;

public class P1 {
    public static void main(String[] args) {
        Path p = Path.of("/home/asha/app/reports/2026/sales.csv");
        System.out.println("toString:     " + p);
        System.out.println("getFileName:  " + p.getFileName());
        System.out.println("getParent:    " + p.getParent());
        System.out.println("getRoot:      " + p.getRoot());
        System.out.println("isAbsolute:   " + p.isAbsolute());
        System.out.println("getNameCount: " + p.getNameCount());
        System.out.println("getName(0):   " + p.getName(0));
        System.out.println("subpath(3,5): " + p.subpath(3, 5));

        Path rel = Path.of("reports", "2026", "sales.csv");
        System.out.println("relative:     " + rel + ", root=" + rel.getRoot() + ", absolute=" + rel.isAbsolute());
        System.out.println("single name parent: " + Path.of("sales.csv").getParent());
        for (Path part : rel) System.out.print("[" + part + "] ");
        System.out.println();
    }
}

Output (on Linux or macOS):

toString:     /home/asha/app/reports/2026/sales.csv
getFileName:  sales.csv
getParent:    /home/asha/app/reports/2026
getRoot:      /
isAbsolute:   true
getNameCount: 6
getName(0):   home
subpath(3,5): reports/2026
relative:     reports/2026/sales.csv, root=null, absolute=false
single name parent: null
[reports] [2026] [sales.csv] 
MethodReturns
getFileName()The last name — the file or folder name itself
getParent()Everything except the last name, or null if there's no parent
getRoot()The root (/ on Unix, C:0 on Windows), or null` for a relative path
isAbsolute()Whether the path starts from a root
getNameCount()How many names there are, not counting the root (6 here)
getName(i)The name at index i, where index 0 is closest to the root
subpath(begin, end)The names from begin (inclusive) to end (exclusive), as a relative path

Every return value is itself a Path (except isAbsolute and getNameCount), so you can call more methods on it. A Path is also Iterable<Path>, so the for loop visits each name in order.

Watch for null: Path.of("sales.csv").getParent() returns null because a single relative name has no parent in the path, even though the file is obviously in some folder on disk. Code such as Files.createDirectories(path.getParent()) throws NullPointerException for such paths; calling toAbsolutePath() first guarantees a parent exists.

Absolute and Relative Paths

Absolute pathRelative path
Starts withA root (/, `C:`)A name
Example/srv/shop/uploads/logo.pnguploads/logo.png
Resolved againstNothing — it's completeThe current working directory (user.dir)
Same meaning on every run?YesOnly if the program is started from the same folder

toAbsolutePath() turns a relative path into an absolute one by prepending the working directory. It doesn't check that the file exists and doesn't remove .. or . segments — it's purely textual.

Path.of(""), the empty path, refers to the working directory itself; Path.of("").toAbsolutePath() is a convenient way to get it as a Path.

Combining Paths: resolve, resolveSibling and relativize

import java.nio.file.*;

public class P2 {
    public static void main(String[] args) {
        Path base = Path.of("/srv/shop");
        System.out.println("resolve:          " + base.resolve("uploads/logo.png"));
        System.out.println("resolve absolute: " + base.resolve("/etc/passwd"));
        Path file = base.resolve("config/app.yaml");
        System.out.println("resolveSibling:   " + file.resolveSibling("app.yaml.bak"));
        System.out.println("relativize:       " + base.relativize(Path.of("/srv/shop/uploads/2026/a.png")));
        System.out.println("relativize up:    " + Path.of("/srv/shop/uploads").relativize(Path.of("/srv/shop/config/app.yaml")));
        Path messy = Path.of("/srv/shop/uploads/../config/./app.yaml");
        System.out.println("normalize:        " + messy.normalize());
        System.out.println("relative normalize: " + Path.of("../../data/./x.csv").normalize());
        System.out.println("startsWith path:  " + Path.of("/srv/shop-backup/x").startsWith(base));
        System.out.println("startsWith string:" + Path.of("/srv/shop-backup/x").toString().startsWith(base.toString()));
        System.out.println("equals:           " + Path.of("/srv/shop/./a").equals(Path.of("/srv/shop/a")));
        System.out.println("equals normalized:" + Path.of("/srv/shop/./a").normalize().equals(Path.of("/srv/shop/a")));
    }
}

Output (on Linux or macOS):

resolve:          /srv/shop/uploads/logo.png
resolve absolute: /etc/passwd
resolveSibling:   /srv/shop/config/app.yaml.bak
relativize:       uploads/2026/a.png
relativize up:    ../config/app.yaml
normalize:        /srv/shop/config/app.yaml
relative normalize: ../../data/x.csv
startsWith path:  false
startsWith string:true
equals:           false
equals normalized:true

resolve

base.resolve(other) appends other to base — the safe, portable way to build a path inside a folder, instead of string concatenation with "/". One rule surprises many developers: if other is absolute, resolve returns other unchanged. base.resolve("/etc/passwd") is simply /etc/passwd. This matters a great deal when other comes from user input (see the practical example below).

resolveSibling

resolveSibling(name) replaces the last name, producing a path in the same folder — ideal for backup copies (app.yaml.bak), temporary files next to the target, or changing an extension.

relativize

a.relativize(b) answers "how do I get from a to b?". From /srv/shop to /srv/shop/uploads/2026/a.png is uploads/2026/a.png; from /srv/shop/uploads to /srv/shop/config/app.yaml requires going up one level first, ../config/app.yaml. It's used to display paths relative to a project folder, or to recreate a folder structure elsewhere: target.resolve(source.relativize(file)). Both paths must be of the same type (both absolute or both relative), otherwise it throws IllegalArgumentException.

normalize

normalize() removes redundant segments: . (the current folder) is dropped, and name/.. pairs cancel out. It's purely textual and doesn't consult the file system, which has two consequences:

  • Leading .. segments in a relative path can't be removed, because there's nothing before them to cancel (../../data/x.csv stays as it is apart from the .).
  • If a folder in the path is a symbolic link, link/.. on disk goes to the link target's parent, not to the folder that contains the link, so the normalized path can differ from where the file system would really go. toRealPath() (below) is the reliable alternative when links may be involved.

startsWith and equals compare names, not text

  • Path.startsWith(Path) compares whole names. /srv/shop-backup/x does not start with /srv/shop, because shop-backup and shop are different names. The string comparison says true, which is the classic bug in hand-written path checks.
  • Path.equals compares the path as written (case-sensitively on Linux, case-insensitively on Windows). /srv/shop/./a and /srv/shop/a describe the same location but aren't equal until normalized. Neither method follows links or checks the disk.

toRealPath() asks the file system for the canonical location: it makes the path absolute, resolves . and .., and follows symbolic links. Unlike the other methods, it requires the file to exist.

import java.io.IOException;
import java.nio.file.*;

public class P3 {
    public static void main(String[] args) throws IOException {
        Path release = Files.createDirectories(Path.of("releases", "v2.4.1"));
        Files.writeString(release.resolve("app.jar"), "jar");
        Path current = Path.of("current");
        Files.deleteIfExists(current);
        Files.createSymbolicLink(current, release);

        Path viaLink = Path.of("current/app.jar");
        System.out.println("toAbsolutePath: " + viaLink.toAbsolutePath());
        System.out.println("toRealPath:     " + viaLink.toRealPath());
        System.out.println("equals:         " + viaLink.equals(Path.of("releases/v2.4.1/app.jar")));
        System.out.println("isSameFile:     " + Files.isSameFile(viaLink, Path.of("releases/v2.4.1/app.jar")));
        try {
            Path.of("missing/file.txt").toRealPath();
        } catch (NoSuchFileException e) {
            System.out.println("toRealPath on a missing path: NoSuchFileException");
        }
    }
}

Output (run in /home/asha/demo on Linux; creating symbolic links on Windows requires Developer Mode or administrator rights):

toAbsolutePath: /home/asha/demo/current/app.jar
toRealPath:     /home/asha/demo/releases/v2.4.1/app.jar
equals:         false
isSameFile:     true
toRealPath on a missing path: NoSuchFileException
  • current is a symbolic link to releases/v2.4.1 — a common deployment layout, where switching versions means repointing one link.
  • toAbsolutePath() only prepends the working directory; the link is still in the path.
  • toRealPath() follows the link and shows where the file physically is. Pass LinkOption.NOFOLLOW_LINKS to resolve the path without following links.
  • equals compares text, so the two paths aren't equal. Files.isSameFile(a, b) asks the file system whether both paths lead to the same file, which is the correct way to check this.

Separators and Operating System Differences

Linux / macOSWindows
Name separator/0 (Java also accepts /` when parsing)
Root/A drive (C:0) or a UNC share (\server\share`)
Case sensitivityCase-sensitive (Report.csv ≠ report.csv)Case-insensitive by default
Path list separator (File.pathSeparator, used in CLASSPATH, PATH):;

FileSystems.getDefault().getSeparator() and File.separator return the current platform's name separator, but you rarely need them: Path.of with several arguments and resolve insert separators automatically. Avoid building paths with string concatenation such as dir + "/" + name — besides portability problems, it allows double separators and makes security checks harder. When parsing, Java also collapses redundant separators, so Path.of("reports//2026") becomes reports/2026, and a trailing separator is dropped.

A backslash is an ordinary character in Linux file names, so Path.of("a0b") on Linux is a single name a\b. Hard-coded Windows-style paths therefore don't work on Linux servers — another reason to build paths from parts.

File Names and Extensions

Path has no method for a file's extension, so applications write a small helper. Edge cases matter: hidden files on Unix start with a dot, some files have no extension, and some have several dots.

import java.nio.file.*;
import java.util.Optional;

public class Ext {
    static Optional<String> extension(Path p) {
        Path name = p.getFileName();
        if (name == null) return Optional.empty();
        String s = name.toString();
        int dot = s.lastIndexOf('.');
        return (dot <= 0 || dot == s.length() - 1) ? Optional.empty() : Optional.of(s.substring(dot + 1));
    }

    static Path withExtension(Path p, String newExt) {
        String s = p.getFileName().toString();
        int dot = s.lastIndexOf('.');
        String stem = dot > 0 ? s.substring(0, dot) : s;
        return p.resolveSibling(stem + "." + newExt);
    }

    public static void main(String[] args) {
        for (String f : new String[] {"report.pdf", "archive.tar.gz", ".gitignore", "README", "photo."}) {
            System.out.println(f + " -> " + extension(Path.of(f)));
        }
        System.out.println(withExtension(Path.of("exports/sales.csv"), "xlsx"));
    }
}

Output:

report.pdf -> Optional[pdf]
archive.tar.gz -> Optional[gz]
.gitignore -> Optional.empty
README -> Optional.empty
photo. -> Optional.empty
exports/sales.xlsx
  • getFileName() is used so that dots in folder names (v2.4.1/README) aren't mistaken for an extension. It returns null for a root path such as /, hence the check.
  • lastIndexOf('.') finds the final dot, so archive.tar.gz gives gz.
  • A dot at index 0 (.gitignore) marks a hidden file rather than an extension, and a trailing dot means an empty extension; both return Optional.empty().
  • withExtension keeps the folder and replaces only the extension using resolveSibling.

The extension is just part of the name; it doesn't guarantee what the file contains. Never trust it for security decisions such as accepting uploads — check the content (or at least Files.probeContentType, which itself is often based on the extension) and enforce a whitelist.

Practical Example: Preventing Path Traversal

Web applications frequently build file paths from user input: "download invoice invoices/1001.pdf" or "show image photos/cat.png". If the input is appended to a base folder without validation, an attacker can request ../config/db.properties and read files outside that folder. This vulnerability is called path traversal (or directory traversal), and it is one of the most common security flaws in file-handling code.

import java.io.IOException;
import java.nio.file.*;

public class Safe {
    static Path safeResolve(Path baseDir, String userPath) {
        Path base = baseDir.toAbsolutePath().normalize();
        Path candidate = base.resolve(userPath).normalize();
        if (!candidate.startsWith(base) || candidate.equals(base)) {
            throw new IllegalArgumentException("path escapes upload folder: " + userPath);
        }
        return candidate;
    }

    public static void main(String[] args) throws IOException {
        Path uploads = Path.of("/srv/shop/uploads");
        String[] requests = {"invoices/1001.pdf", "../config/db.properties", "/etc/passwd",
                             "a/../../uploads-old/x.pdf", "photos/./cat.png", ""};
        for (String r : requests) {
            try {
                System.out.println("OK      " + r + " -> " + safeResolve(uploads, r));
            } catch (IllegalArgumentException e) {
                System.out.println("BLOCKED " + e.getMessage());
            }
        }
    }
}

Output:

OK      invoices/1001.pdf -> /srv/shop/uploads/invoices/1001.pdf
BLOCKED path escapes upload folder: ../config/db.properties
BLOCKED path escapes upload folder: /etc/passwd
BLOCKED path escapes upload folder: a/../../uploads-old/x.pdf
OK      photos/./cat.png -> /srv/shop/uploads/photos/cat.png
BLOCKED path escapes upload folder: 

How each part of the check defends against a specific attack:

  1. The base is made absolute and normalized first, so the comparison is done between two clean, comparable paths.
  2. resolve then normalize computes where the request would really point. ../config/db.properties normalizes to /srv/shop/config/db.properties.
  3. startsWith(base) compares whole path names, so the result must be inside /srv/shop/uploads. This blocks ../config/..., and it also blocks a/../../uploads-old/x.pdf, which normalizes to /srv/shop/uploads-old/x.pdf. A string-based startsWith would have wrongly accepted that one, because the text /srv/shop/uploads-old begins with /srv/shop/uploads.
  4. Absolute input is blocked because resolve returns an absolute argument unchanged: /etc/passwd resolves to /etc/passwd, which isn't under the base.
  5. candidate.equals(base) rejects an empty request, which would otherwise point at the upload folder itself rather than a file.
  6. Harmless redundancy is allowed: photos/./cat.png normalizes to a valid path inside the folder.

If the upload folder may contain symbolic links (for instance, one pointing to /etc), the textual check isn't enough. In that case, once the file is known to exist, compare candidate.toRealPath() with base.toRealPath() as well. The strongest design avoids user-supplied paths altogether: store files under generated names (such as UUIDs) and look up the stored name by an ID from the database, so the user never chooses a file-system path at all.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java File Paths and get answers drawn from it.

Signed-in readers only.