在c# /.NET中有System.IO.Path.Combine()的Java等价程序吗?或者任何代码来完成这个?
这个静态方法将一个或多个字符串组合成一个路径。
在c# /.NET中有System.IO.Path.Combine()的Java等价程序吗?或者任何代码来完成这个?
这个静态方法将一个或多个字符串组合成一个路径。
当前回答
也许来晚了,但我想分享一下我对这件事的看法。我不喜欢把整个库都拉来做这样的事情。相反,我使用Builder模式,并允许方便地链式附加(更多)调用。它甚至允许混合文件和字符串,并且可以很容易地扩展到支持路径。此外,它可以在Linux、Macintosh等上自动正确地处理不同的路径分隔符。
public class Files {
public static class PathBuilder {
private File file;
private PathBuilder ( File root ) {
file = root;
}
private PathBuilder ( String root ) {
file = new File(root);
}
public PathBuilder append ( File more ) {
file = new File(file, more.getPath()) );
return this;
}
public PathBuilder append ( String more ) {
file = new File(file, more);
return this;
}
public File buildFile () {
return file;
}
}
public static PathBuilder buildPath ( File root ) {
return new PathBuilder(root);
}
public static PathBuilder buildPath ( String root ) {
return new PathBuilder(root);
}
}
用法示例:
File root = File.listRoots()[0];
String hello = "hello";
String world = "world";
String filename = "warez.lha";
File file = Files.buildPath(root).append(hello).append(world)
.append(filename).buildFile();
String absolute = file.getAbsolutePath();
生成的绝对值将包含如下内容:
/hello/world/warez.lha
或者甚至:
A:\hello\world\warez.lha
其他回答
下面是一个处理多路径部分和边缘条件的解决方案:
public static String combinePaths(String ... paths)
{
if ( paths.length == 0)
{
return "";
}
File combined = new File(paths[0]);
int i = 1;
while ( i < paths.length)
{
combined = new File(combined, paths[i]);
++i;
}
return combined.getPath();
}
假设所有给定的路径都是绝对路径。您可以按照下面的代码片段来合并这些路径。
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。
为了加强JodaStephen的回答,Apache Commons IO有FilenameUtils。示例(Linux):
assert org.apache.commons.io.FilenameUtils.concat("/home/bob", "work\\stuff.log") == "/home/bob/work/stuff.log"
它是平台独立的,可以生成系统所需的任何分隔符。
在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);
主要的答案是使用File对象。然而,Commons IO确实有一个类FilenameUtils可以做这种事情,比如concat()方法。