Paul Taylor
Paul Taylor

Reputation: 13190

In Java elegant way to get each section of path up to Root

Is there a more elegant way to get each section of path up to Root e.g given

E:\AllMusic\The Shadows\The Very Best of The Shadows

I want to get

E:\AllMusic\The Shadows\The Very Best of The Shadows
E:\AllMusic\The Shadows
E:\AllMusic
E:\

I have done it with code below (I am just printing out path but in real code need to do something with these paths), but it seems very convoluted. I do want to do this properly, and note it has to work with Windows/Unix etc so I dont want to be doing clever hacks with Strings. Im using Java 8.

System.out.println(folder);
while(folder.getNameCount()>1)
{
    if(folder.getRoot()!=null)
    {
        folder = folder.getRoot().resolve(folder.subpath(0, folder.getNameCount() - 1));
    }
    System.out.println(folder);
}
if(folder.getRoot()!=null)
{
    System.out.println(folder.getRoot()); 
}

Upvotes: 1

Views: 99

Answers (2)

dorado
dorado

Reputation: 1525

Use the methods getNameCount() and getName(int index) of java.nio.Path

File f = new File("E:\AllMusic\The Shadows\The Very Best of The Shadows");
Path p = f.toPath();
int pathElements = p.getNameCount();

for (int i = 0; i < pathElements; ++i) {
    Path subPath = p.subpath(0, pathElements - i - 1);
}

Upvotes: 1

steffen
steffen

Reputation: 16938

Maybe this:

Path p = Path.of("E:\\AllMusic\\The Shadows\\The Very Best of The Shadows");
do {
    System.out.println(p);
} while ((p = p.getParent()) != null);

Output:

E:\AllMusic\The Shadows\The Very Best of The Shadows
E:\AllMusic\The Shadows
E:\AllMusic
E:\

Upvotes: 5

Related Questions