在c# /.NET中有System.IO.Path.Combine()的Java等价程序吗?或者任何代码来完成这个?
这个静态方法将一个或多个字符串组合成一个路径。
在c# /.NET中有System.IO.Path.Combine()的Java等价程序吗?或者任何代码来完成这个?
这个静态方法将一个或多个字符串组合成一个路径。
当前回答
在Java 7中,你应该使用resolve:
Path newPath = path.resolve(childPath);
虽然对于使用不必要的不同API的File来说,NIO2 Path类似乎有点多余,但实际上它更加优雅和健壮。
注意,Paths.get()(由其他人建议)没有重载获取Path,并且执行Paths.get(Path . tostring (), childPath)与resolve()不是一回事。从Paths.get()文档:
注意,虽然这个方法非常方便,但使用它将意味着对默认文件系统的假定引用,并限制了调用代码的实用性。因此,它不应该用于用于灵活重用的库代码中。一个更灵活的选择是使用一个现有的Path实例作为锚,例如: 路径dir =… 路径Path = dir.resolve("file");
要解决的姐妹函数是优秀的相对化:
Path childPath = path.relativize(newPath);
其他回答
假设所有给定的路径都是绝对路径。您可以按照下面的代码片段来合并这些路径。
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。
该解决方案提供了一个接口,用于连接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"
在Java 7中,你应该使用resolve:
Path newPath = path.resolve(childPath);
虽然对于使用不必要的不同API的File来说,NIO2 Path类似乎有点多余,但实际上它更加优雅和健壮。
注意,Paths.get()(由其他人建议)没有重载获取Path,并且执行Paths.get(Path . tostring (), childPath)与resolve()不是一回事。从Paths.get()文档:
注意,虽然这个方法非常方便,但使用它将意味着对默认文件系统的假定引用,并限制了调用代码的实用性。因此,它不应该用于用于灵活重用的库代码中。一个更灵活的选择是使用一个现有的Path实例作为锚,例如: 路径dir =… 路径Path = dir.resolve("file");
要解决的姐妹函数是优秀的相对化:
Path childPath = path.relativize(newPath);
您应该使用一个用于表示文件系统路径的类,而不是保持所有内容都基于字符串。
如果你使用的是Java 7或Java 8,你应该强烈考虑使用Java .nio.file. path;路径。解析可用于将一个路径与另一个路径或与字符串组合。Paths助手类也很有用。例如:
Path path = Paths.get("foo", "bar", "baz.txt");
如果需要适应java -7之前的环境,可以使用java.io。文件,像这样:
File baseDirectory = new File("foo");
File subDirectory = new File(baseDirectory, "bar");
File fileInDirectory = new File(subDirectory, "baz.txt");
如果稍后希望它以字符串形式返回,可以调用getPath()。实际上,如果您真的想模仿Path。结合起来,你可以这样写:
public static String combine(String path1, String path2)
{
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
主要的答案是使用File对象。然而,Commons IO确实有一个类FilenameUtils可以做这种事情,比如concat()方法。