Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the relative path of the file to a folder using java [duplicate]

Tags:

java

file-io

Possible Duplicate:
How to construct a relative path in Java from two absolute paths (or URLs)?

using java, is there method to return the relative path of a file to a given folder?

like image 655
user496949 Avatar asked Feb 24 '23 18:02

user496949


1 Answers

There's no method included with Java to do what you want. Perhaps there's a library somewhere out there that does it (I can't think of any offhand, and Apache Commons IO doesn't appear to have it). You could use this or something like it:

// returns null if file isn't relative to folder
public static String getRelativePath(File file, File folder) {
    String filePath = file.getAbsolutePath();
    String folderPath = folder.getAbsolutePath();
    if (filePath.startsWith(folderPath)) {
        return filePath.substring(folderPath.length() + 1);
    } else {
        return null;
    }
}
like image 168
WhiteFang34 Avatar answered Mar 22 '23 22:03

WhiteFang34