在c# /.NET中有System.IO.Path.Combine()的Java等价程序吗?或者任何代码来完成这个?
这个静态方法将一个或多个字符串组合成一个路径。
在c# /.NET中有System.IO.Path.Combine()的Java等价程序吗?或者任何代码来完成这个?
这个静态方法将一个或多个字符串组合成一个路径。
当前回答
该解决方案提供了一个接口,用于连接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"
其他回答
下面是一个处理多路径部分和边缘条件的解决方案:
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();
}
您应该使用一个用于表示文件系统路径的类,而不是保持所有内容都基于字符串。
如果你使用的是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。分隔符,即将工作取决于代码运行的操作系统:
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
我知道距离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"
它是平台独立的,可以生成系统所需的任何分隔符。