如何在Java中组合路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/412380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to combine paths in Java?
提问by
Is there a Java equivalent for System.IO.Path.Combine()
in C#/.NET? Or any code to accomplish this?
System.IO.Path.Combine()
在 C#/.NET 中是否有 Java 等价物?或者任何代码来完成这个?
This static method combines one or more strings into a path.
这种静态方法将一个或多个字符串组合成一个路径。
回答by Jon Skeet
Rather than keeping everything string-based, you should use a class which is designed to represent a file system path.
您应该使用一个旨在表示文件系统路径的类,而不是保留所有基于字符串的内容。
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:
如果您使用的是 Java 7 或 Java 8,则应强烈考虑使用java.nio.file.Path
; Path.resolve
可用于将一个路径与另一个路径或字符串组合。该Paths
辅助类是有用的。例如:
Path path = Paths.get("foo", "bar", "baz.txt");
If you need to cater for pre-Java-7 environments, you can use java.io.File
, like this:
如果您需要迎合 Java-7 之前的环境,您可以使用java.io.File
,如下所示:
File baseDirectory = new File("foo");
File subDirectory = new File(baseDirectory, "bar");
File fileInDirectory = new File(subDirectory, "baz.txt");
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:
如果您想稍后将其作为字符串返回,您可以调用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();
}
回答by JodaStephen
The main answer is to use File objects. However Commons IOdoes have a class FilenameUtilsthat can do this kind of thing, such as the concat()method.
主要的答案是使用 File 对象。但是Commons IO确实有一个类FilenameUtils可以做这种事情,比如concat()方法。
回答by alpian
To enhance JodaStephen's answer, Apache Commons IO has FilenameUtils which does this. Example (on Linux):
为了增强 JodaStephen 的回答,Apache Commons IO 有 FilenameUtils 可以做到这一点。示例(在 Linux 上):
assert org.apache.commons.io.FilenameUtils.concat("/home/bob", "work\stuff.log") == "/home/bob/work/stuff.log"
It's platform independent and will produce whatever separators your system needs.
它是独立于平台的,可以生产您的系统需要的任何分隔符。
回答by Bill
Here's a solution which handles multiple path parts and edge conditions:
这是一个处理多个路径部分和边缘条件的解决方案:
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();
}
回答by isNaN1247
I know its a long time since Jon's original answer, but I had a similar requirement to the OP.
我知道距离 Jon 的原始答案已经很长时间了,但我对 OP 有类似的要求。
By way of extending Jon's solution I came up with the following, which will take one or more path segments takes as many path segments that you can throw at it.
通过扩展 Jon 的解决方案,我提出了以下解决方案,它将采用一个或多个路径段,并采用您可以投入的尽可能多的路径段。
Usage
用法
Path.combine("/Users/beardtwizzle/");
Path.combine("/", "Users", "beardtwizzle");
Path.combine(new String[] { "/", "Users", "beardtwizzle", "arrayUsage" });
Code here for others with a similar problem
在这里为其他有类似问题的人编写代码
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();
}
}
回答by Aleksandr Dubinsky
In Java 7, you should use resolve
:
在 Java 7 中,您应该使用resolve
:
Path newPath = path.resolve(childPath);
While the NIO2 Path class may seem a bit redundant to File with an unnecessarily different API, it is in fact subtly more elegant and robust.
虽然 NIO2 Path 类对于具有不必要的不同 API 的 File 来说似乎有点多余,但实际上它更加优雅和健壮。
Note that Paths.get()
(as suggested by someone else) doesn't have an overload taking a Path
, and doing Paths.get(path.toString(), childPath)
is NOT the same thing as resolve()
. From the Paths.get()
docs:
请注意Paths.get()
(正如其他人所建议的)没有重载 a Path
,并且 doPaths.get(path.toString(), childPath)
与resolve()
. 从Paths.get()
文档:
Note that while this method is very convenient, using it will imply an assumed reference to the default FileSystem and limit the utility of the calling code. Hence it should not be used in library code intended for flexible reuse. A more flexible alternative is to use an existing Path instance as an anchor, such as:
Path dir = ... Path path = dir.resolve("file");
请注意,虽然此方法非常方便,但使用它会暗示对默认 FileSystem 的假定引用并限制调用代码的效用。因此,不应在旨在灵活重用的库代码中使用它。更灵活的替代方法是使用现有的 Path 实例作为锚点,例如:
Path dir = ... Path path = dir.resolve("file");
The sister function to resolve
is the excellent relativize
:
姐妹功能toresolve
是优秀的relativize
:
Path childPath = path.relativize(newPath);
回答by Gismo Ranas
If you do not need more than strings, you can use com.google.common.io.Files
如果您不需要多个字符串,则可以使用com.google.common.io.Files
Files.simplifyPath("some/prefix/with//extra///slashes" + "file//name")
to get
要得到
"some/prefix/with/extra/slashes/file/name"
回答by Maksim Kostromin
platform independent approach (uses File.separator, ie will works depends on operation system where code is running:
平台无关的方法(使用 File.separator,即取决于运行代码的操作系统:
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
回答by Stephan Henningsen
Late to the party perhaps, but I wanted to share my take on this. I'm using a Builder pattern and allow conveniently chained append
calls. It can easily be extended to support working with Path
objects as well.
也许聚会迟到了,但我想分享我对此的看法。我正在使用 Builder 模式并允许方便地链接append
调用。它也可以很容易地扩展为支持使用Path
对象。
public class Files {
public static class PathBuilder {
private File file;
private PathBuilder ( File root ) {
file = root;
}
private PathBuilder ( String root ) {
file = new File(root);
}
public PathBuilder append ( File more ) {
file = new File(file, more.getPath()) );
return this;
}
public PathBuilder append ( String more ) {
file = new File(file, more);
return this;
}
public File buildFile () {
return file;
}
}
public static PathBuilder buildPath ( File root ) {
return new PathBuilder(root);
}
public static PathBuilder buildPath ( String root ) {
return new PathBuilder(root);
}
}
Example of usage:
用法示例:
File root = File.listRoots()[0];
String hello = "hello";
String world = "world";
String filename = "warez.lha";
File file = Files.buildPath(root).append(hello).append(world)
.append(filename).buildFile();
String absolute = file.getAbsolutePath();
The resulting absolute
will contain something like:
结果absolute
将包含如下内容:
/hello/world/warez.lha
or maybe even:
或者甚至:
A:\hello\world\warez.lha
回答by rootExplorr
This also works in Java 8 :
这也适用于 Java 8:
Path file = Paths.get("Some path");
file = Paths.get(file + "Some other path");