3

Given I have two File objects I can think of the following implementation:

public File convertToRelative(File home, File file) {
    final String homePath = home.getAbsolutePath();
    final String filePath = file.getAbsolutePath();

    // Only interested in converting file path that is a 
    // direct descendants of home path
    if (!filePath.beginsWith(homePath)) {
        return file;
    }

    return new File(filePath.substring(homePath.length()+1));
}

Is there some smarter way of converting an absolute file path to a relative file path?

Possible Duplicate:

How to construct a relative path in java from two absolute paths or urls

Community
  • 1
  • 1
Spoike
  • 119,724
  • 44
  • 140
  • 158

1 Answers1

24

This question was asked before here

Here is the answer just in case

String path = "/var/data/stuff/xyz.dat";
String base = "/var/data";
String relative = new File(base).toURI().relativize(new File(path).toURI()).getPath();
// relative == "stuff/xyz.dat"
Community
  • 1
  • 1
Lombo
  • 11,847
  • 2
  • 20
  • 27