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

Paul Taylor :

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()); 
}
steffen :

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:\

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325923&siteId=1