如何在Java中组合路径? [英] How to combine paths in Java?
问题描述
<$ c $是否有Java等价物c> C#/ .NET中的System.IO.Path.Combine() ?或者任何代码来完成这个?
Is there a Java equivalent for System.IO.Path.Combine()
in C#/.NET? Or any code to accomplish this?
这个静态方法将一个或多个字符串组合成一个路径。
This static method combines one or more strings into a path.
推荐答案
您应该使用一个用于表示文件系统路径的类,而不是保持基于字符串的所有内容。
Rather than keeping everything string-based, you should use a class which is designed to represent a file system path.
如果你'重新使用Java 7或Java 8,你应该强烈考虑使用 java.nio.file.Path
; Path.resolve
可用于将一个路径与另一个路径或字符串组合在一起。 路径
辅助类也很有用。例如:
If you're using Java 7 or Java 8, you should strongly consider using java.nio.file.Path
; Path.resolve
can be used to combine one path with another, or with a string. The Paths
helper class is useful too. For example:
Path path = Paths.get("foo", "bar", "baz.txt");
如果您需要迎合Java-7之前的环境,可以使用 java.io.File
,像这样:
If you need to cater for pre-Java-7 environments, you can use java.io.File
, like this:
File baseDirectory = new File("foo");
File subDirectory = new File(baseDirectory, "bar");
File fileInDirectory = new File(subDirectory, "baz.txt");
如果您希望以后再将其作为字符串返回,可以调用 getPath( )
。实际上,如果你真的想模仿 Path.Combine
,你可以写下这样的东西:
If you want it back as a string later, you can call getPath()
. Indeed, if you really wanted to mimic Path.Combine
, you could just write something like:
public static String combine(String path1, String path2)
{
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
这篇关于如何在Java中组合路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!