In Java 11 and later, Path.of() is the preferred way to create Path instances, effectively replacing Paths.get().
Here is how you can use it:
1. Basic Usage (Replacing Paths.get)
The syntax is almost identical. It accepts a string or a sequence of strings to join into a path.
package org.kodejava.nio;
import java.nio.file.Path;
public class PathExample {
public static void main(String[] args) {
// Using a single string
Path path1 = Path.of("C:/logs/app.log");
// Using multiple strings (varargs) to join paths
Path path2 = Path.of("C:", "logs", "app.log");
System.out.println(path2); // Outputs: C:\logs\app.log (on Windows)
}
}
2. Working with URIs
Path.of() also has an overload that accepts a URI object, just like Paths.get(URI uri).
import java.net.URI;
import java.nio.file.Path;
Path pathFromUri = Path.of(URI.create("file:///C:/logs/app.log"));
Why use Path.of() instead of Paths.get()?
- Cleaner API:
Pathis the primary interface.Path.of()keeps the logic within the interface itself rather than relying on a separate utility class (Paths). - Modern Standard:
Paths.get()was introduced in Java 7 as a bridge. Java 11 introducedPath.of()as the modern, static factory method on the interface. - Consistency: Most modern Java APIs (like
List.of(),Set.of()) use this naming convention.
