Spo*_*ike 3 java relative-path absolute-path
鉴于我有两个File对象,我可以想到以下实现:
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));
}
Run Code Online (Sandbox Code Playgroud)
有没有更聪明的方法将绝对文件路径转换为相对文件路径?
可能重复:
Lom*_*mbo 23
这个问题在此之前被问过
以下是答案,以防万一
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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14531 次 |
| 最近记录: |