Java Path create
In this tutorial we’re going to show different ways to create Path to filesystem objects introduced in Java 7.
Since introduction in Java 7 java.nio.file.Path has become standard interface for working with filesystem paths and superseded old java.io.File class.
Path interface extends Comparable<Path>, Iterable<Path>, and Watchable, which means that it can be compared with other paths, iterated over, and watched for changes. Read Java WatchService to learn more about watching paths!
Create Path examples
Construct using Paths.get() passing full path:
Path path = Paths.get("/proc/version"); System.out.println("Path from absolute name: " + path);
Result:
Path from absolute name: /proc/version
Create using Path.get(), but from separate parts:
Path path = Paths.get("/proc", "version"); System.out.println("Path from parts: " + path);
Result:
Path from parts: /proc/version
Create using FileSystem (works the same as above):
// The same as above: Path path = FileSystems.getDefault().getPath("/proc", "version"); System.out.println("Path from FileSystem: " + path);
Result:
Path from FileSystem: /proc/version
Create from URI:
Path path = Paths.get(URI.create("file:///proc/version")); System.out.println("Path from URI: " + path);
Result:
Path from URI: /proc/version
API:
- java.nio.file.FileSystems
- java.nio.file.Path
- java.nio.file.Paths
Want to learn more cool stuff about Java IO? Check out Java IO Tutorial!