猿问

如何在Java中合并路径?

System.IO.Path.Combine()在C#/。NET中是否有Java等效项?或任何代码来实现这一目标?


此静态方法将一个或多个字符串组合到路径中。


qq_笑_17
浏览 4820回答 3
3回答

炎炎设计

而不是让所有内容都基于字符串,您应该使用旨在表示文件系统路径的类。如果您使用的是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();}

幕布斯6054654

在Java 7中,您应该使用resolve:Path newPath = path.resolve(childPath);尽管NIO2 Path类对于使用不必要的不同API的File似乎有点多余,但实际上它更优雅,更强大。请注意,Paths.get()(根据其他人的建议)并没有带有的重载Path,并且这样做Paths.get(path.toString(), childPath)与并不相同resolve()。从Paths.get()文档:请注意,尽管此方法非常方便,但使用它将意味着假定对默认FileSystem的引用并限制了调用代码的实用性。因此,不应在旨在灵活重用的库代码中使用它。一种更灵活的选择是使用现有的Path实例作为锚点,例如:Path dir = ...Path path = dir.resolve("file");对姐妹的作用resolve是优异的relativize:Path childPath = path.relativize(newPath);

PIPIONE

自从乔恩(Jon)的原始答案以来,我就已经知道了很长时间,但是我对OP有类似的要求。通过扩展Jon的解决方案,我提出了以下内容,它将采用一个或多个路径段,而您可以将其扔给它。用法Path.combine("/Users/beardtwizzle/");Path.combine("/", "Users", "beardtwizzle");Path.combine(new String[] { "/", "Users", "beardtwizzle", "arrayUsage" });在这里为其他有类似问题的人编码public class Path {&nbsp; &nbsp; public static String combine(String... paths)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; File file = new File(paths[0]);&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 1; i < paths.length ; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; file = new File(file, paths[i]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return file.getPath();&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答