在c# /.NET中有System.IO.Path.Combine()的Java等价程序吗?或者任何代码来完成这个?

这个静态方法将一个或多个字符串组合成一个路径。


当前回答

为了加强JodaStephen的回答,Apache Commons IO有FilenameUtils。示例(Linux):

assert org.apache.commons.io.FilenameUtils.concat("/home/bob", "work\\stuff.log") == "/home/bob/work/stuff.log"

它是平台独立的,可以生成系统所需的任何分隔符。

其他回答

假设所有给定的路径都是绝对路径。您可以按照下面的代码片段来合并这些路径。

String baseURL = "\\\\host\\testdir\\";
String absoluteFilePath = "\\\\host\\testdir\\Test.txt";;
String mergedPath = Paths.get(baseURL, absoluteFilePath.replaceAll(Matcher.quoteReplacement(baseURL), "")).toString();

输出路径为\\host\testdir\Test.txt。

我知道距离Jon最初的回答已经有很长时间了,但我对OP有类似的要求。

通过扩展Jon的解决方案,我想出了下面的方法,这将占用一个或多个路径段占用尽可能多的路径段。

使用

Path.combine("/Users/beardtwizzle/");
Path.combine("/", "Users", "beardtwizzle");
Path.combine(new String[] { "/", "Users", "beardtwizzle", "arrayUsage" });

这里为其他有类似问题的人编写代码

public class Path {
    public static String combine(String... paths)
    {
        File file = new File(paths[0]);

        for (int i = 1; i < paths.length ; i++) {
            file = new File(file, paths[i]);
        }

        return file.getPath();
    }
}

为了加强JodaStephen的回答,Apache Commons IO有FilenameUtils。示例(Linux):

assert org.apache.commons.io.FilenameUtils.concat("/home/bob", "work\\stuff.log") == "/home/bob/work/stuff.log"

它是平台独立的,可以生成系统所需的任何分隔符。

如果只需要字符串,可以使用com.google.common.io.Files

Files.simplifyPath("some/prefix/with//extra///slashes" + "file//name")

得到

"some/prefix/with/extra/slashes/file/name"

该解决方案提供了一个接口,用于连接String[]数组中的路径片段。它使用java.io.File。文件(父字符串,子字符串):

    public static joinPaths(String[] fragments) {
        String emptyPath = "";
        return buildPath(emptyPath, fragments);
    }

    private static buildPath(String path, String[] fragments) {
        if (path == null || path.isEmpty()) {
            path = "";
        }

        if (fragments == null || fragments.length == 0) {
            return "";
        }

        int pathCurrentSize = path.split("/").length;
        int fragmentsLen = fragments.length;

        if (pathCurrentSize <= fragmentsLen) {
            String newPath = new File(path, fragments[pathCurrentSize - 1]).toString();
            path = buildPath(newPath, fragments);
        }

        return path;
    }

然后你可以这样做:

String[] fragments = {"dir", "anotherDir/", "/filename.txt"};
String path = joinPaths(fragments);

返回:

"/dir/anotherDir/filename.txt"