Path: naming a file in Java
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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)); }}marks.txt data\marks.txt data\2025\sem1\marks.txt data\marks.txt Same path? true
What this code does
- Each argument of
Path.ofis one name. Java joins them with the separator of the computer:\on Windows, so macOS and Linux printdata/marks.txtinstead. Paths.getbuilds an equalPath, soequalsistrue. PreferPath.ofin 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.
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.
PS C:\Users\Priya> echo $HOMEC:\Users\Priya
Example 2 · Reading the parts of a path
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()); }}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 pathcollege/2025/fees; callinggetFileName()on it gives justfees, the folder the receipt is in.getRoot()isnullbecause this path does not start at a drive or/. A single name has no parent, sogetParent()isnulltoo: check for it before calling methods on the result.
Example 3 · Finding a file's extension from its name
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)); } }}poster.png -> png budget.xlsx -> xlsx backup.tar.gz -> gz README -> (none)
What this code does
getFileName()returns aPath;toString()turns it into aStringsolastIndexOfandsubstringcan be used.- Taking the name after the last dot gives
gzforbackup.tar.gz. Using the whole path string instead of the file name would break for folders with dots, such asv1.2/README.
getNameCount()andgetName(i)give the number of names and the name at indexi(from 0).getParent()returnsnullwhen there is only one name, such asPath.of("receipt.pdf").getRoot()returnsnullfor a path that does not start at a root, such asdata/marks.txt.- A
Pathworks 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?
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
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); }}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.ofsucceeds with no file on disk. OnlyFiles.sizelooks at the disk, and it throwsNoSuchFileException, which names the missing file.Files.writeString(path, text)creates the file with that text (the Reading and Writing Text Files module covers it). AfterFiles.deletethe file is gone, but thePathobject 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.
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.
File oldStyle = new File("data", "marks.txt");Path modern = oldStyle.toPath(); // File -> PathFile again = modern.toFile(); // Path -> FileThe 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
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); } }}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()andtoFile()convert between the old and new types, so you can usePathin your code and still call an old library that wants aFile.File.delete()only saysfalse.Files.deletethrowsNoSuchFileExceptionwith 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