Absolute to Relative File Path in Java
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"
Troj
I'm a jack of most trades residing in Sweden and usually involved with full-stack web development technologies. I work for tretton37 as a contractor, my list of clients includes among others Sony and IKEA. I dabble in open source software and have many projects in my Github repository and my Bitbucket repository, among many: RefluxJS - Library for uni-directional data flows, inspired by Facebook's Flux In the little free time that I have, all kinds of stuff happen such as drawing pretty pictures, perform ball juggling, play a guitar, hack on games, and solve a Rubik's cube.
Updated on June 04, 2022Comments
-
Troj almost 2 years
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