在c# /.NET中有System.IO.Path.Combine()的Java等价程序吗?或者任何代码来完成这个?
这个静态方法将一个或多个字符串组合成一个路径。
在c# /.NET中有System.IO.Path.Combine()的Java等价程序吗?或者任何代码来完成这个?
这个静态方法将一个或多个字符串组合成一个路径。
当前回答
主要的答案是使用File对象。然而,Commons IO确实有一个类FilenameUtils可以做这种事情,比如concat()方法。
其他回答
如果只需要字符串,可以使用com.google.common.io.Files
Files.simplifyPath("some/prefix/with//extra///slashes" + "file//name")
得到
"some/prefix/with/extra/slashes/file/name"
平台独立的方法(使用File。分隔符,即将工作取决于代码运行的操作系统:
java.nio.file.Paths.get(".", "path", "to", "file.txt")
// relative unix path: ./path/to/file.txt
// relative windows path: .\path\to\filee.txt
java.nio.file.Paths.get("/", "path", "to", "file.txt")
// absolute unix path: /path/to/filee.txt
// windows network drive path: \\path\to\file.txt
java.nio.file.Paths.get("C:", "path", "to", "file.txt")
// absolute windows path: C:\path\to\file.txt
这也适用于Java 8:
Path file = Paths.get("Some path");
file = Paths.get(file + "Some other path");
主要的答案是使用File对象。然而,Commons IO确实有一个类FilenameUtils可以做这种事情,比如concat()方法。
下面是一个处理多路径部分和边缘条件的解决方案:
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();
}