We understand shortcuts to be the . (current directory) and .. (parent directory) notations. This kind of path can be normalized via the normalize() method. This method eliminates redundancies such as . and directory/..:
Path path = Paths.get(
"C:/learning/packt/chapters/../JavaModernChallenge.pdf")
.normalize();
Path path = Paths.get(
"C:/learning/./packt/chapters/../JavaModernChallenge.pdf")
.normalize();
Path path = FileSystems.getDefault()
.getPath("/learning/./packt", "JavaModernChallenge.pdf")
.normalize();
Path path = Path.of(
"C:/learning/packt/chapters/../JavaModernChallenge.pdf")
.normalize();
Path path = Path.of(
"C:/learning/./packt/chapters/../JavaModernChallenge.pdf")
.normalize();
Without normalization, the redundant parts of the path will not be removed.
For creating paths that are 100% compatible with the current operating system, we can rely on FileSystems.getDefault().getPath(), or a combination of File.separator (system-dependent default name separator character) and File.listRoots() (the available filesystem roots). For relative paths, we can rely on the following examples:
private static final String FILE_SEPARATOR = File.separator;
Alternatively, we can rely on getSeparator():
private static final String FILE_SEPARATOR
= FileSystems.getDefault().getSeparator();
// relative to current working folder
Path path = Paths.get("learning",
"packt", "JavaModernChallenge.pdf");
Path path = Path.of("learning",
"packt", "JavaModernChallenge.pdf");
Path path = Paths.get(String.join(FILE_SEPARATOR, "learning",
"packt", "JavaModernChallenge.pdf"));
Path path = Path.of(String.join(FILE_SEPARATOR, "learning",
"packt", "JavaModernChallenge.pdf"));
// relative to the file store root
Path path = Paths.get(FILE_SEPARATOR + "learning",
"packt", "JavaModernChallenge.pdf");
Path path = Path.of(FILE_SEPARATOR + "learning",
"packt", "JavaModernChallenge.pdf");
We can also do the same for absolute paths:
Path path = Paths.get(File.listRoots()[0] + "learning",
"packt", "JavaModernChallenge.pdf");
Path path = Path.of(File.listRoots()[0] + "learning",
"packt", "JavaModernChallenge.pdf");
The list of root directories can be obtained via FileSystems as well:
FileSystems.getDefault().getRootDirectories()