Search code examples
javapathnio2

How do I extract subpath neatly accounting for root and no root folders on java


I have a Path object and a String object, the Path object represents part of the starting path represented by the filename

e.g for the filename /Music/Beatles/Help.mp3 the Path object may be

/
/Music
/Music/Beatles

this simple method returns the part of the path minus the basefolder

public String getPathRemainder(Path path, String filename)
{
        if(baseFolder.getNameCount()==0)
        {
            return song.getFilename().substring(baseFolder.toString().length());
        }
        else
        {
            return song.getFilename().substring(baseFolder.toString().length()+File.separator.length());
    }

i.e

Music/Beatles/Help.mp3
Beatles/Help.mp3
Help.mp3

but although simple its rather messy as I have to account for the fact that if the base folder is a root folder it ends with '/' (on unix) but not none root paths.

Im sure there is a neater approach, but I cant see it.


Solution

  • Using java.nio available since Java 7:

    Path file = Paths.get("/Music/Beatles/Help.mp3");
    
    Path dir1 = Paths.get("/");
    Path dir2 = Paths.get("/Music");
    Path dir3 = Paths.get("/Music/Beatles");
    
    System.out.println(dir1.relativize(file));
    System.out.println(dir2.relativize(file));
    System.out.println(dir3.relativize(file));
    

    You get:

    Music/Beatles/Help.mp3
    Beatles/Help.mp3
    Help.mp3