المطلق إلى مسار الملف النسبي في جافا [مكررة
-
24-09-2019 - |
سؤال
هذا السؤال لديه بالفعل إجابة هنا:
بالنظر إلى أن لدي اثنين 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));
}
هل هناك طريقة أكثر ذكاءً لتحويل مسار الملف المطلق إلى مسار الملف النسبي؟
تكرار ممكن:
المحلول
تم طرح هذا السؤال من قبل هنا
هنا الجواب فقط في حالة
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"
لا تنتمي إلى StackOverflow