是否有 System.IO.Path.Combine()
的 Java 等效项?在 C#/.NET 中?或者有什么代码可以做到这一点?
此静态方法将一个或多个字符串组合成一个路径。
最佳答案
您应该使用旨在表示文件系统路径的类,而不是让所有内容都基于字符串。
如果您使用的是 Java 7 或 Java 8,您应该强烈考虑使用 java.nio.file.Path
; Path.resolve
可用于将一条路径与另一条路径或与字符串组合。 Paths
助手类也很有用。例如:
Path path = Paths.get("foo", "bar", "baz.txt");
如果您需要满足 Java-7 之前的环境,您可以使用 java.io.File
,像这样:
File baseDirectory = new File("foo");
File subDirectory = new File(baseDirectory, "bar");
File fileInDirectory = new File(subDirectory, "baz.txt");
如果您希望稍后将其作为字符串返回,您可以调用 getPath()
。事实上,如果你真的想模仿 Path.Combine
,你可以写这样的:
public static String combine(String path1, String path2)
{
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
关于java - 如何在Java中组合路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/412380/