Java File and Path: Creating Paths and Converting Between Them (OCP 21)
Files and paths for the OCP 21 exam: absolute and relative paths, . and .., symbolic links, creating java.io.File and NIO.2 Path objects with Path.of, Paths.get, FileSystems and URIs, converting between them, and the File methods that map to Path and Files.
kvi5hnuCode Sprout team member8 min readOn this page
Everything so far has lived in memory and vanished when the program ended. To keep data between runs, programs read and write files. Java has two APIs for this:
- the original
java.ioAPI, built around theFileclass (Java 1.0); - NIO.2 in
java.nio.file, built around thePathinterface and theFileshelper class (Java 7).
Both are on the exam, and they work together. New code should prefer NIO.2. This article covers how to refer to files and directories. The following articles cover what you can do with them.
File system basics
- A file holds data. A directory holds files and other directories. Java mostly treats them alike, so "file" often means "file or directory" in this chapter.
- The root directory is the top of the tree:
/on Linux and macOS, or a drive such asC:\on Windows. - A path names a file or directory. Its parts are joined by the name separator (often just called the file separator),
/on Unix and\on Windows.System.getProperty("file.separator")andFile.separatorboth return it. Don't confuse it withFile.pathSeparator(:or;), which separates entries in a class path.
An absolute path starts at the root and fully identifies the location. A relative path is interpreted from the current working directory, the directory the JVM was started in (System.getProperty("user.dir")). The exam uses these conventions:
- starts with
/: absolute, for example/opt/garden/beds/roses.txt; - starts with a drive letter such as
C:: absolute; - anything else: relative, for example
seeds/tulip.txt.
Two path symbols can appear in either kind of path:
| Symbol | Meaning |
|---|---|
. | the current directory |
.. | the parent of the current directory |
From /opt/garden/beds, the relative path ../seeds/tulip.txt means /opt/garden/seeds/tulip.txt, and ./roses.txt means /opt/garden/beds/roses.txt. A path like /opt/garden/beds/../seeds/./tulip.txt contains redundant parts. normalize() (article 85) removes them.

A symbolic link is a special file that points to another file or directory. The operating system usually follows it transparently. java.io.File has no support for symbolic links, while NIO.2 can create, detect and optionally not follow them.
A name tells you nothing about what kind of entry it is. notes.txt can be a directory, and compost, with no extension, can be a regular file. On the exam, don't assume a path is a file or a directory unless the question says so.
Creating a File
File is a class, created with a constructor:
File a = new File("/opt/garden/beds/roses.txt");
File b = new File("/opt/garden", "beds/roses.txt"); // parent String, child
File c = new File(new File("/opt/garden"), "beds/roses.txt"); // parent File, child
All three refer to the same location. If the parent is null, it's ignored, and the constructor acts like the one-argument version. There's no no-argument constructor.
Creating a File object never touches the disk. It's just a name. The file may not exist, and exists() checks whether it does.
Creating a Path
Path is an interface, so new Path(...) doesn't compile. Use a factory method:
Path p1 = Path.of("/opt/garden/beds/roses.txt");
Path p2 = Path.of("/opt", "garden", "beds", "roses.txt"); // varargs, joined with the separator
The signature is Path.of(String first, String... more), so at least one argument is required. Other ways that might appear on the exam:
Path p3 = Paths.get("/opt", "garden", "beds", "roses.txt"); // older helper class
Path p4 = FileSystems.getDefault().getPath("/opt/garden/beds/roses.txt");
Path p5 = Path.of(URI.create("file:///opt/garden/beds/roses.txt")); // from a URI
Paths.get()takes the same arguments asPath.of(). Its Javadoc says the class may be deprecated in a future release, so preferPath.of().Path.of()actually delegates toFileSystems.getDefault().getPath(...).- A URI starts with a scheme, such as
file:for local files. The URI must be absolute, so a relative URI throwsIllegalArgumentException. A scheme with no installed file system provider, such ashttps:, throwsFileSystemNotFoundException. The JDK doesn't treat web addresses as file systems. path.toUri()converts the other way, for example tofile:///opt/garden/beds/roses.txt.
Like File, creating a Path doesn't check the disk.
Converting between File and Path
File legacy = new File("seeds/tulip.txt");
Path modern = legacy.toPath();
File back = modern.toFile();
This makes it easy to pass File objects from older libraries to NIO.2 code, and the reverse.
The same operations in both APIs
File puts everything in instance methods. NIO.2 splits the work: Path instance methods deal with the name, and static Files methods deal with the file system.
| Task | java.io.File | NIO.2 |
|---|---|---|
| Name of the file or directory | getName() | path.getFileName() (returns a Path) |
Parent, or null if none | getParent() (String) / getParentFile() | path.getParent() |
| Is the path absolute? | isAbsolute() | path.isAbsolute() |
| Absolute version | getAbsolutePath() (String) | path.toAbsolutePath() |
| Does it exist? | exists() | Files.exists(path) |
| Is it a regular file? | isFile() | Files.isRegularFile(path) |
| Is it a directory? | isDirectory() | Files.isDirectory(path) |
| Size in bytes | length() | Files.size(path) |
| Last modified | lastModified() (long) | Files.getLastModifiedTime(path) (FileTime) |
| Directory contents | listFiles() / list() | Files.list(path) (Stream<Path>) |
| Create one directory | mkdir() | Files.createDirectory(path) |
| Create with missing parents | mkdirs() | Files.createDirectories(path) |
| Rename or move | renameTo(dest) | Files.move(source, target) |
| Delete | delete() | Files.delete(path) / Files.deleteIfExists(path) |
Note the names that differ: isFile()/isRegularFile(), length()/size(), getName()/getFileName(), mkdir()/createDirectory(). Files methods take a Path, never a File, so Files.exists(new File("x")) doesn't compile.
Different failure styles
The two APIs report problems differently:
Filemethods rarely throw. They returnfalse,0ornullinstead:delete()on a missing file returnsfalse,length()returns0,mkdir()on an existing directory returnsfalse, andlistFiles()on a missing directory returnsnull.Filesmethods that read or change the file system throw the checkedIOException, or a subclass that says exactly what went wrong:Files.sizeon a missing file throwsNoSuchFileException, andFiles.createDirectoryon an existing directory throwsFileAlreadyExistsException. The test methods,exists,isDirectoryandisRegularFile, don't throw. They returnfalse.
So NIO.2 code usually needs throws IOException or a try/catch. In exchange, you find out why something failed.
Listing a directory
try (Stream<Path> entries = Files.list(dir)) {
entries.forEach(p -> System.out.println(p.getFileName()));
}
Files.list() returns a lazy Stream<Path> that reads entries as needed. It holds an open directory handle, so close it with try-with-resources. File.listFiles() reads the whole directory into an array at once.
What's current
Path.of()(Java 11) is the preferred factory.Paths.get()still works and isn't deprecated as of Java 25, but its Javadoc recommendsPath.of().- New code should use NIO.2.
java.io.Fileisn't deprecated, but it lacks symbolic-link support, file attributes and precise exceptions. Files.writeStringandFiles.readString(Java 11), used in the complete example, are covered in article 88.
Exam traps from this article
A complete example
A garden planner refers to the same file in every way the APIs allow. It creates a small real directory tree in a temporary folder, asks the same questions with File and with Path/Files, and compares how the two APIs report failures. The temporary folder is deleted at the end.
Absolute temporary paths differ on every run, so the program prints locations relative to its temporary folder.
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Stream;
public class Solution {
/** Legacy java.io.File version: few checked exceptions, returns null or false on trouble. */
static void describeWithFile(File file, File base) {
System.out.println(" exists: " + file.exists() + ", isDirectory: " + file.isDirectory()
+ ", isFile: " + file.isFile());
System.out.println(" getName: " + file.getName() + ", parent: " + base.toPath().relativize(file.getParentFile().toPath()));
if (file.isFile()) {
System.out.println(" length: " + file.length() + " bytes");
} else {
String[] names = file.list();
Arrays.sort(names);
System.out.println(" contents: " + Arrays.toString(names));
}
}
/** NIO.2 version: static Files methods take a Path, and several throw IOException. */
static void describeWithPath(Path path, Path base) throws IOException {
System.out.println(" exists: " + Files.exists(path) + ", isDirectory: " + Files.isDirectory(path)
+ ", isRegularFile: " + Files.isRegularFile(path));
System.out.println(" getFileName: " + path.getFileName() + ", parent: " + base.relativize(path.getParent()));
if (Files.isRegularFile(path)) {
System.out.println(" size: " + Files.size(path) + " bytes");
} else {
try (Stream<Path> entries = Files.list(path)) { // lazily read; must be closed
System.out.println(" contents: " + entries.map(p -> p.getFileName().toString()).sorted().toList());
}
}
}
public static void main(String[] args) throws IOException {
System.out.println("== 1. Creating File objects (nothing touches the disk)");
File f1 = new File("/opt/garden/beds/roses.txt");
File f2 = new File("/opt/garden", "beds/roses.txt");
File f3 = new File(new File("/opt/garden"), "beds/roses.txt");
File f4 = new File((File) null, "/opt/garden/beds/roses.txt"); // null parent is ignored
System.out.println(" all four equal: " + (f1.equals(f2) && f2.equals(f3) && f3.equals(f4)));
System.out.println(" exists on this computer: " + f1.exists());
System.out.println("\n== 2. Creating Path objects");
Path p1 = Path.of("/opt/garden/beds/roses.txt");
Path p2 = Path.of("/opt", "garden", "beds", "roses.txt"); // varargs, joined with the separator
Path p3 = Paths.get("/opt", "garden", "beds", "roses.txt"); // older helper, same result
Path p4 = FileSystems.getDefault().getPath("/opt/garden/beds/roses.txt");
Path p5 = Path.of(URI.create("file:///opt/garden/beds/roses.txt")); // file: URIs need an absolute path
System.out.println(" all five equal: " + (p1.equals(p2) && p2.equals(p3) && p3.equals(p4) && p4.equals(p5)));
System.out.println(" toUri(): " + p1.toUri());
System.out.println(" file.separator: " + System.getProperty("file.separator")
+ " (File.separator: " + File.separator + ")");
try {
Path.of(URI.create("garden/roses.txt"));
} catch (IllegalArgumentException e) {
System.out.println(" Path.of(relative URI) -> IllegalArgumentException");
}
try {
Path.of(URI.create("https://example.com/roses.txt"));
} catch (FileSystemNotFoundException e) {
System.out.println(" Path.of(https URI) -> FileSystemNotFoundException (no https file system installed)");
}
System.out.println("\n== 3. Converting between File and Path");
File legacy = new File("seeds/tulip.txt");
Path modern = legacy.toPath();
File back = modern.toFile();
System.out.println(" toPath(): " + modern + ", toFile(): " + back + ", round trip equal: " + legacy.equals(back));
System.out.println("\n== 4. Absolute and relative, with path symbols");
Path relative = Path.of("beds/../seeds/./tulip.txt");
System.out.println(" " + relative + " isAbsolute: " + relative.isAbsolute());
System.out.println(" toAbsolutePath() starts at the working directory: "
+ relative.toAbsolutePath().startsWith(Path.of(System.getProperty("user.dir"))));
System.out.println(" " + p1 + " isAbsolute: " + p1.isAbsolute() + ", root: " + p1.getRoot());
System.out.println(" new File(\"seeds\").isAbsolute(): " + new File("seeds").isAbsolute()
+ ", getAbsolutePath() ends with: " + new File("seeds").getAbsolutePath().endsWith(File.separator + "seeds"));
System.out.println("\n== 5. The same questions, asked with File and with Path/Files");
Path base = Files.createTempDirectory("garden");
try {
Path beds = Files.createDirectories(base.resolve("garden/beds"));
Files.writeString(beds.resolve("roses.txt"), "12 red\n3 white\n");
Files.writeString(beds.resolve("herbs.txt"), "basil\n");
Files.createDirectory(beds.resolve("notes.txt")); // a DIRECTORY with an extension
Files.writeString(beds.resolve("compost"), ""); // a FILE without one
System.out.println(" File: garden/beds/roses.txt");
describeWithFile(beds.resolve("roses.txt").toFile(), base.toFile());
System.out.println(" Path: garden/beds/roses.txt");
describeWithPath(beds.resolve("roses.txt"), base);
System.out.println(" File: garden/beds");
describeWithFile(beds.toFile(), base.toFile());
System.out.println(" Path: garden/beds");
describeWithPath(beds, base);
System.out.println("\n== 6. Failure styles: File returns values, Files throws");
File missing = beds.resolve("orchids.txt").toFile();
System.out.println(" File.delete() on a missing file: " + missing.delete());
System.out.println(" File.length() on a missing file: " + missing.length());
System.out.println(" File.mkdir() on an existing directory: " + beds.toFile().mkdir());
System.out.println(" Files.deleteIfExists(missing): " + Files.deleteIfExists(missing.toPath()));
try {
Files.size(missing.toPath());
} catch (NoSuchFileException e) {
System.out.println(" Files.size(missing) -> NoSuchFileException");
}
try {
Files.createDirectory(beds);
} catch (FileAlreadyExistsException e) {
System.out.println(" Files.createDirectory(existing) -> FileAlreadyExistsException");
}
System.out.println(" notes.txt is a directory: " + Files.isDirectory(beds.resolve("notes.txt"))
+ ", compost is a regular file: " + Files.isRegularFile(beds.resolve("compost")));
} finally {
try (Stream<Path> all = Files.walk(base)) { // delete deepest entries first
for (Path p : all.sorted(Comparator.reverseOrder()).toList()) Files.delete(p);
}
}
System.out.println(" temporary directory removed: " + Files.notExists(base));
}
}
Output:
== 1. Creating File objects (nothing touches the disk)
all four equal: true
exists on this computer: false
== 2. Creating Path objects
all five equal: true
toUri(): file:///opt/garden/beds/roses.txt
file.separator: / (File.separator: /)
Path.of(relative URI) -> IllegalArgumentException
Path.of(https URI) -> FileSystemNotFoundException (no https file system installed)
== 3. Converting between File and Path
toPath(): seeds/tulip.txt, toFile(): seeds/tulip.txt, round trip equal: true
== 4. Absolute and relative, with path symbols
beds/../seeds/./tulip.txt isAbsolute: false
toAbsolutePath() starts at the working directory: true
/opt/garden/beds/roses.txt isAbsolute: true, root: /
new File("seeds").isAbsolute(): false, getAbsolutePath() ends with: true
== 5. The same questions, asked with File and with Path/Files
File: garden/beds/roses.txt
exists: true, isDirectory: false, isFile: true
getName: roses.txt, parent: garden/beds
length: 15 bytes
Path: garden/beds/roses.txt
exists: true, isDirectory: false, isRegularFile: true
getFileName: roses.txt, parent: garden/beds
size: 15 bytes
File: garden/beds
exists: true, isDirectory: true, isFile: false
getName: beds, parent: garden
contents: [compost, herbs.txt, notes.txt, roses.txt]
Path: garden/beds
exists: true, isDirectory: true, isRegularFile: false
getFileName: beds, parent: garden
contents: [compost, herbs.txt, notes.txt, roses.txt]
== 6. Failure styles: File returns values, Files throws
File.delete() on a missing file: false
File.length() on a missing file: 0
File.mkdir() on an existing directory: false
Files.deleteIfExists(missing): false
Files.size(missing) -> NoSuchFileException
Files.createDirectory(existing) -> FileAlreadyExistsException
notes.txt is a directory: true, compost is a regular file: true
temporary directory removed: true
Points to notice:
- The four
Fileobjects and the fivePathobjects pointed to the same place, and none of them needed the file to exist. Path.ofwith anhttpsURI failed withFileSystemNotFoundException, because there's no web file system provider.File.length()andFiles.size()agreed on 15 bytes.isFile()matchedisRegularFile().File.delete()andmkdir()reported failure asfalse, whileFiles.size()andFiles.createDirectory()threw specificIOExceptionsubclasses.notes.txtwas a directory andcomposta regular file. Names tell you nothing.- The cleanup deleted entries deepest-first, because a directory must be empty before it can be deleted (article 86).
Common questions
Should I use File or Path?
Use Path with Files in new code. Use toPath() and toFile() at the boundary with older libraries that still expect File.
Is Path.of("roses.txt") relative to my source file?
No. It's relative to the working directory of the running JVM, which is usually where you launched java. It has nothing to do with where the .java or .class file is.
Do I need double backslashes for Windows paths?
In a Java string literal, yes: "C:\\data\\notes.txt", because \ starts an escape sequence. Forward slashes work on Windows too.
Summary
- Paths are absolute (starting at the root) or relative (from the working directory).
.is the current directory, and..is the parent. - Create a
Filewith its constructors, and aPathwithPath.of(),Paths.get(),FileSystems.getDefault().getPath()or afile:URI. - Neither object checks the disk when created. Convert with
file.toPath()andpath.toFile(). Fileuses instance methods that returnfalse,0ornullon failure. NIO.2 usesPathfor names and staticFilesmethods that throwIOException.- Know the paired names:
getName/getFileName,isFile/isRegularFile,length/size,listFiles/list,mkdir(s)/createDirector(y|ies),renameTo/move.
Practice quiz
Test yourself with the File and Path quiz: 10 exam-style questions with explanations.
Previous: Java Parallel Streams: Parallel Decomposition, Reductions and Ordering (OCP 21)
Next: Java Path Methods: normalize, resolve, relativize and Files Basics (OCP 21)
Related reading
- Java Parallel Streams: Parallel Decomposition, Reductions and Ordering (OCP 21)
- Java Concurrent Collections and Threading Problems: Deadlock, Starvation and Livelock (OCP 21)
- Java Locks: ReentrantLock, tryLock, ReadWriteLock and CyclicBarrier (OCP 21)
- Java Thread Safety: Race Conditions, volatile, Atomic Classes and synchronized (OCP 21)
- Java ExecutorService: Runnable, Callable, Future, invokeAll and Scheduling (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.