Extracting parts of paths in Java
Asked Answered
D

6

11

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.

Daytoday answered 14/3, 2013 at 13:20 Comment(3)
What doesn't work using Path.subpath()?Interim
Using Path.subpath(0, 2) gives me home/Dara. I would like to be able to say something like Path.subpath(myPath.length() - 3, myPath.length() - 1 to get baz/qux.Daytoday
Can't you use Path.getNameCount() for the length?Interim
F
13

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.

Fendley answered 14/3, 2013 at 13:24 Comment(0)
B
7

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().

Bronchia answered 14/3, 2013 at 13:39 Comment(0)
J
4

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);
Jequirity answered 24/9, 2017 at 10:18 Comment(0)
Q
2

You could just split the String or use a StringTokenizer.

Quillon answered 14/3, 2013 at 13:21 Comment(3)
True, I am doing that now but I would be more comfortable using a more generic way.Daytoday
what do you mean by more generic way?Groats
Make sure to use System.getProperty("file.separator") and not specifically a "/" in your calls.Herriot
K
1

File.getParent() will remove the filename.

And the path separator you will get with: System.getProperty("file.separator").

Then you can use String.split() to get each part of the path.

Korella answered 14/3, 2013 at 13:23 Comment(0)
J
1

To get path parts in Koltin

fun subPaths(path: Path, levels: Int): List<Path> {
    return path.runningReduce { acc, value -> acc.resolve(value) }.take(levels)
}
Joacima answered 5/7, 2023 at 17:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.