4

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?

Community
  • 1
  • 1
user496949
  • 83,087
  • 147
  • 309
  • 426

2 Answers2

9

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;
    }
}
WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
  • That would assume the file is somewhere inside that folder. Splitting the path using the path separator would allow you to traverse each subfolder and compare them (as easy as looping in the string array) – Aleadam Mar 21 '11 at 05:36
  • @Aleadam: subfolders are handled. E.g. if file is `/1/2/3/a.txt` and folder is `/1/2` it'll return `3/a.txt`. – WhiteFang34 Mar 21 '11 at 05:41
  • Yes, but if the file is in /1/4/a.txt, it'll return /4/a.txt, which is wrong. – Aleadam Mar 21 '11 at 14:19
  • @Aleadam: give it a try yourself, for me `getRelativePath(new File("/1/2/3/a.txt"), new File("/1/2"))` returns `3/a.txt` and `getRelativePath(new File("/1/4/a.txt"), new File("/1/2"))` returns `null`. – WhiteFang34 Mar 21 '11 at 16:29
-1

between File.getPath() and String.split() you should be all set to do it.

http://download.oracle.com/javase/6/docs/api/java/io/File.html#getPath%28%29

http://download.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29

Aleadam
  • 40,203
  • 9
  • 86
  • 108