首页 > 解决方案 > 替换 Java 路径的第一部分

问题描述

在 Java 中,我正在寻找一种解决方案,用另一个路径替换路径的第一部分。

我找到的唯一解决方案有点难看,你可以在subPath下面的方法中找到它:

import java.nio.file.Path;
import java.nio.file.Paths;

public class TestPath {

    static Path subPath(Path newPrefix, Path pathWithOldPrefix){ ;
        Path result;
        if(pathWithOldPrefix.getNameCount() > 1) {
            result = newPrefix.resolve(pathWithOldPrefix.subpath(1, pathWithOldPrefix.getNameCount()));
        }else{
            result = newPrefix;
        }
        return result;
    }

    public static void main(String[] args) {
        //display "/newPrefix/myPath"
        System.out.println(subPath(Paths.get("/newPrefix"), Paths.get("/oldPrefix/myPath")));

        //display "/newPrefix
        System.out.println(subPath(Paths.get("/newPrefix"), Paths.get("/oldPrefix/")));

    }
}

有什么更好的解决方案吗?

标签: java

解决方案


Path pathWithOldPrefix = Paths.get("/oldPrefix/myPath");
Path oldPrefix = Paths.get("/oldPrefix"); // Or maybe
Path oldPrefix = pathWithOldPrefix.subpath(0, 1);
Path newPrefix = Paths.get("/newPrefix");

Path relative = oldPrefix.relativize(pathWithOldPrefix); // myPath
Path newPath = newPrefix.resolve(relative);              // /newPrefix/myPath
Path newPath2 = newPrefix.resolve(oldPrefix.relativize(pathWithOldPrefix));
                                                         // /newPrefix/myPath

所以relativize删除了 oldPrefix (注意参数的顺序)。然后resolve添加到前缀。


推荐阅读