I want to navigate the file system and get the path to the child of a directory (if exists) without the root.
For example:
- Input:
Users/Documents/SVG
- Output:
Documents/SVG
My solution so far is to hardcode a string manipulation of the path:
JavaScript
x
/**
* Return the path to the immediate child of a directory.
*
* @param path to a directory
* @return path to the child without the root
*/
public static String removeRootFolderInPath(String path) {
ArrayList<String> tmp = new ArrayList<>(Arrays.asList(path.split("/")));
if (tmp.size() > 1) {
tmp.remove(0);
}
path = String.join("/", tmp);
return path;
}
Is there a more elegant way to do this?
Advertisement
Answer
Path.relativize() can help
JavaScript
Path
parent=Path.of("Users"),
child=Path.of("Users","Documents","SVG");
Path relative=parent.relativize(child);
You can convert this Path back to an File as follows
JavaScript
relative.toFile()
And you can concert any File to an Path as follows
JavaScript
File f=
Path p=f.toPath();
For better operations on files take a look at the Files class