Search code examples
javafilepathfilepath

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.


Solution

  • Not yet pretty, however, you guess the direction:

    File parent = file.getParentFile();
    File parent2 = parent.getParentFile();
    parent2.getName() + System.getProperty("path.separator") + parent.getName()
    

    Another option:

    final int len = path.getNameCount();
    path.subpath(len - 3, len - 1)
    

    Edit: You should either check len or catch the IllegalArgumentException to make your code more robust.