Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting parts of paths in Java

I have a file path like this:

/home/Dara/Desktop/foo/bar/baz/qux/file.txt

In Java, I would like to be able to get the top two folders. Ie. baz/qux regardless of file path length or operating system (File path separators such as / : and \). I have tried to use the subpath() method in Paths but I can't seem to find a generic way to get the length of the file path.

like image 438
Dara Java Avatar asked Mar 14 '13 13:03

Dara Java


2 Answers

The methods getNameCount() and getName(int index) of java.nio.Path should help you:

File f = new File("/home/Dara/Desktop/foo/bar/baz/qux/file.txt");
Path p = f.toPath();
int pathElements = p.getNameCount();
String topOne = p.getName(pathElements-2).toString();
String topTwo = p.getName(pathElements-3).toString();

Please be aware, that the result of getNameCount() should be checked for validity, before using it as an index for getName().

like image 188
Juergen Hartelt Avatar answered Oct 19 '22 12:10

Juergen Hartelt


Using subpath and getNameCount.

    Path myPath = Paths.get("/home/Dara/Desktop/foo/bar/baz/qux/file.txt");
    Path subPath = myPath.subpath(myPath.getNameCount() -3, myPath.getNameCount() -1);
like image 21
Will Humphreys Avatar answered Oct 19 '22 12:10

Will Humphreys