Skip to lesson

Path: naming a file in Java

I'm on:

Showing steps for Windows. They are marked “On Windows” below.

A Path is a Java object that holds the name and location of a file or folder, such as data/marks.txt. It lives in the java.nio.file package and is where all modern file work in Java starts.

Path.of and the older Paths.get

A Path is an object that names a file or folder location, such as reports/marks.txt; creating a Path does not create or check the file.

Path.of builds a Path from one string or from several parts: Path.of("data", "marks.txt"). Each part is one folder or file name, and Java joins them with the right separator for your computer.

Example 1 · Path.of and Paths.get build the same path

PathOfDemo.javaJava
import java.nio.file.Path;import java.nio.file.Paths;
public class PathOfDemo {    public static void main(String[] args) {        Path one = Path.of("marks.txt");        Path two = Path.of("data", "marks.txt");        Path three = Path.of("data", "2025", "sem1", "marks.txt");        Path old = Paths.get("data", "marks.txt");
        System.out.println(one);        System.out.println(two);        System.out.println(three);        System.out.println(old);        System.out.println("Same path? " + two.equals(old));    }}
Sample output (Windows; macOS and Linux print / instead of \)
marks.txt
data\marks.txt
data\2025\sem1\marks.txt
data\marks.txt
Same path? true

What this code does

  • Each argument of Path.of is one name. Java joins them with the separator of the computer: \ on Windows, so macOS and Linux print data/marks.txt instead.
  • Paths.get builds an equal Path, so equals is true. Prefer Path.of in new code (Java 11 and later).

A separator is the character between names: \ on Windows, / on macOS and Linux. Because Java adds it for you, the parts form never needs a slash in your code. Paths.get(...) does exactly the same job. It came first (Java 7); Path.of was added in Java 11 and is the one to use in new code. You will still see Paths.get in older projects and answers online.

Path is an interface, so you never write new Path(...). You always ask Path.of for one.

getFileName, getParent and getRoot

A path is a list of names: college/2025/fees/receipt.pdf has four. getFileName returns the last name, getParent returns everything before it, and getRoot returns the start of an absolute path, such as C:\ on Windows or / on macOS and Linux.

The path college/2025/fees/receipt.pdf is four names with indexes 0 to 3. getParent() is college/2025/fees, getFileName() is receipt.pdf, getNameCount() is 4, getName(1) is 2025 and getRoot() is null.

On Windows

On Windows your home folder is C:\Users\Priya, so C:\Users\Priya\reports\marks.csv has the root C:\ and four names: Users, Priya, reports and marks.csv. getParent() is C:\Users\Priya\reports.

Windows PowerShell
PS C:\Users\Priya> echo $HOMEC:\Users\Priya

Example 2 · Reading the parts of a path

PathPartsDemo.javaJava
import java.nio.file.Path;
public class PathPartsDemo {    public static void main(String[] args) {        Path receipt = Path.of("college", "2025", "fees", "receipt.pdf");
        System.out.println("File name    : " + receipt.getFileName());        System.out.println("Parent folder: " + receipt.getParent().getFileName());        System.out.println("Name count   : " + receipt.getNameCount());        System.out.println("First name   : " + receipt.getName(0));        System.out.println("Root         : " + receipt.getRoot());
        System.out.print("All names    :");        for (Path name : receipt) {            System.out.print(" [" + name + "]");        }        System.out.println();
        Path single = Path.of("receipt.pdf");        System.out.println("Parent of a single name: " + single.getParent());    }}
Output
File name    : receipt.pdf
Parent folder: fees
Name count   : 4
First name   : college
Root         : null
All names    : [college] [2025] [fees] [receipt.pdf]
Parent of a single name: null

What this code does

  • getParent() returns the path college/2025/fees; calling getFileName() on it gives just fees, the folder the receipt is in.
  • getRoot() is null because this path does not start at a drive or /. A single name has no parent, so getParent() is null too: check for it before calling methods on the result.

Example 3 · Finding a file's extension from its name

ExtensionDemo.javaJava
import java.nio.file.Path;import java.util.List;
public class ExtensionDemo {    static String extension(Path file) {        String name = file.getFileName().toString();        int dot = name.lastIndexOf('.');        if (dot == -1) {            return "(none)";        }        return name.substring(dot + 1);    }
    public static void main(String[] args) {        List<Path> uploads = List.of(                Path.of("fest", "poster.png"),                Path.of("fest", "budget.xlsx"),                Path.of("fest", "backup.tar.gz"),                Path.of("fest", "README"));
        for (Path p : uploads) {            System.out.println(p.getFileName() + " -> " + extension(p));        }    }}
Output
poster.png -> png
budget.xlsx -> xlsx
backup.tar.gz -> gz
README -> (none)

What this code does

  • getFileName() returns a Path; toString() turns it into a String so lastIndexOf and substring can be used.
  • Taking the name after the last dot gives gz for backup.tar.gz. Using the whole path string instead of the file name would break for folders with dots, such as v1.2/README.
  • getNameCount() and getName(i) give the number of names and the name at index i (from 0).
  • getParent() returns null when there is only one name, such as Path.of("receipt.pdf").
  • getRoot() returns null for a path that does not start at a root, such as data/marks.txt.
  • A Path works in a for-each loop: for (Path name : path) visits each name in order.

All three return a Path, not a String. Call toString() when you need text, for example to check the file extension.

Predict the output

Read the names of a path

Read the code and pick what it prints.

Round 1 of 4

What does this program print?

import java.nio.file.Path;
public class PathQuiz {
public static void main(String[] args) {
Path p = Path.of("college", "2025", "fees", "receipt.pdf");
System.out.println(p.getFileName());
}
}

A Path is only a name: the file may not exist

Creating a Path does not touch the disk. Path.of("hall-ticket.pdf") works even if no such file exists, in the same way that writing an address on an envelope does not build the house.

Example 4 · A Path to a file that does not exist

OnlyANameDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class OnlyANameDemo {    public static void main(String[] args) throws IOException {        Path ticket = Path.of("hall-ticket-2025.txt");        System.out.println("Path made: " + ticket);        System.out.println("File exists? " + Files.exists(ticket));
        try {            long bytes = Files.size(ticket);            System.out.println("Size: " + bytes);        } catch (IOException e) {            System.out.println("Cannot read size: " + e);        }
        Files.writeString(ticket, "Roll 21, Hall B");        System.out.println("After writing, exists? " + Files.exists(ticket));        System.out.println("Size: " + Files.size(ticket) + " bytes");
        Files.delete(ticket);        System.out.println("After delete, exists? " + Files.exists(ticket));        System.out.println("The Path is still: " + ticket);    }}
Output
Path made: hall-ticket-2025.txt
File exists? false
Cannot read size: java.nio.file.NoSuchFileException: hall-ticket-2025.txt
After writing, exists? true
Size: 15 bytes
After delete, exists? false
The Path is still: hall-ticket-2025.txt

What this code does

  • Path.of succeeds with no file on disk. Only Files.size looks at the disk, and it throws NoSuchFileException, which names the missing file.
  • Files.writeString(path, text) creates the file with that text (the Reading and Writing Text Files module covers it). After Files.delete the file is gone, but the Path object is unchanged: it was only ever a name.

The disk is checked only when you ask the Files class to do something: Files.exists(path), Files.size(path), Files.delete(path). Files is a class full of static methods that work on real files; the next lessons of this module use it a lot. If the file is missing, those methods return false or throw an IOException such as NoSuchFileException. The only error Path.of itself can give is InvalidPathException, when the text cannot be a name at all on this computer, for example marks?.txt on Windows.

Hold paths as Path objects and check the disk at the moment you use the file. A file can appear or vanish at any time.

The old java.io.File class and toPath

Before Java 7, files were named with java.io.File: new File("data", "marks.txt"). Like Path, a File is only a name. Its methods, such as exists() and delete(), work on the disk directly.

Java
File oldStyle = new File("data", "marks.txt");Path modern = oldStyle.toPath();     // File -> PathFile again = modern.toFile();        // Path -> File

The problem is error reporting. file.delete() just returns false when it fails, so you never learn why. Files.delete(path) throws an exception that names the reason: no such file, folder not empty, or access denied.

Example 5 · File.delete hides the reason, Files.delete tells you

FileVsPathDemo.javaJava
import java.io.File;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class FileVsPathDemo {    public static void main(String[] args) {        File oldStyle = new File("data", "marks.txt");        Path modern = oldStyle.toPath();        System.out.println("Same as Path.of? " + modern.equals(Path.of("data", "marks.txt")));        System.out.println("Back to File: " + modern.toFile().getName());
        File notes = new File("missing-notes.txt");        boolean deleted = notes.delete();        System.out.println("File.delete returned: " + deleted);
        try {            Files.delete(notes.toPath());        } catch (IOException e) {            System.out.println("Files.delete says: " + e);        }    }}
Output
Same as Path.of? true
Back to File: marks.txt
File.delete returned: false
Files.delete says: java.nio.file.NoSuchFileException: missing-notes.txt

What this code does

  • toPath() and toFile() convert between the old and new types, so you can use Path in your code and still call an old library that wants a File.
  • File.delete() only says false. Files.delete throws NoSuchFileException with the file name, so the caller knows exactly what went wrong.

Old libraries still take and return File. Convert at the edge: file.toPath() gives a Path, and path.toFile() gives a File back.

Next step

Check your understanding

10 quick questions