سؤال

هذا السؤال لديه بالفعل إجابة هنا:

بالنظر إلى أن لدي اثنين 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));
}

هل هناك طريقة أكثر ذكاءً لتحويل مسار الملف المطلق إلى مسار الملف النسبي؟

تكرار ممكن:

كيفية بناء مسار نسبي في جافا من مسارين مطلقين أو عناوين URL

هل كانت مفيدة؟

المحلول

تم طرح هذا السؤال من قبل هنا

هنا الجواب فقط في حالة

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"
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top