How to construct a relative path in Java from two absolute paths (or URLs)?

前端 未结 22 2305
小蘑菇
小蘑菇 2020-11-22 10:30

Given two absolute paths, e.g.

/var/data/stuff/xyz.dat
/var/data

How can one create a relative path that uses the second path as its base?

22条回答
  •  死守一世寂寞
    2020-11-22 11:11

    If Paths is not available for JRE 1.5 runtime or maven plugin

    package org.afc.util;
    
    import java.io.File;
    import java.util.LinkedList;
    import java.util.List;
    
    public class FileUtil {
    
        public static String getRelativePath(String basePath, String filePath)  {
            return getRelativePath(new File(basePath), new File(filePath));
        }
    
        public static String getRelativePath(File base, File file)  {
    
            List bases = new LinkedList();
            bases.add(0, base.getName());
            for (File parent = base.getParentFile(); parent != null; parent = parent.getParentFile()) {
                bases.add(0, parent.getName());
            }
    
            List files = new LinkedList();
            files.add(0, file.getName());
            for (File parent = file.getParentFile(); parent != null; parent = parent.getParentFile()) {
                files.add(0, parent.getName());
            }
    
            int overlapIndex = 0;
            while (overlapIndex < bases.size() && overlapIndex < files.size() && bases.get(overlapIndex).equals(files.get(overlapIndex))) {
                overlapIndex++;
            }
    
            StringBuilder relativePath = new StringBuilder();
            for (int i = overlapIndex; i < bases.size(); i++) {
                relativePath.append("..").append(File.separatorChar);
            }
    
            for (int i = overlapIndex; i < files.size(); i++) {
                relativePath.append(files.get(i)).append(File.separatorChar);
            }
    
            relativePath.deleteCharAt(relativePath.length() - 1);
            return relativePath.toString();
        }
    
    }
    

提交回复
热议问题