如何在Java中组合路径? [英] How to combine paths in Java?
问题描述
System 是否有 Java 等价物.IO.Path.Combine()
在 C#/.NET 中?或者任何代码来完成这个?
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
可用于将一个路径与另一个路径或字符串组合.路径
helper 类也很有用.例如:
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屋!