在 Java 中连接路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34459486/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:40:38  来源:igfitidea点击:

Joining paths in Java

java

提问by cybertextron

In PythonI can join two paths with os.path.join:

Python我可以加入两条路径os.path.join

os.path.join("foo", "bar") # => "foo/bar"

I'm trying to achive the same in Java, without worrying if the OSis Unix, Solarisor Windows:

我正在尝试在 Java 中实现相同的目标,而不必担心OSUnix,SolarisWindows

public static void main(String[] args) {
    Path currentRelativePath = Paths.get("");
    String current_dir = currentRelativePath.toAbsolutePath().toString();
    String filename = "data/foo.txt";
    Path filepath = currentRelativePath.resolve(filename);

    // "data/foo.txt"
    System.out.println(filepath);

}

I was expecting that Path.resolve( )would join my current directory /home/user/testwith data/foo.txtmaking /home/user/test/data/foo.txt. What am I getting wrong?

我期待那Path.resolve( )会加入我的当前目录/home/user/testdata/foo.txt制作/home/user/test/data/foo.txt。我怎么了?

采纳答案by YoungHobbit

Even though the original solution for getting the current directory using the empty Stringworks. But is recommended to use the user.dirproperty for current directory and user.homefor home directory.

即使使用empty String作品获取当前目录的原始解决方案。但建议user.dir对当前目录和user.home主目录使用该属性。

Path currentPath = Paths.get(System.getProperty("user.dir"));
Path filePath = Paths.get(currentPath.toString(), "data", "foo.txt");
System.out.println(filePath.toString());

output:

输出:

/Users/user/coding/data/foo.txt


From Java Pathclass Documentation:

来自 Java Path类文档:

A Path is considered to be an empty path if it consists solely of one name element that is empty. Accessing a file using an empty path is equivalent to accessing the default directoryof the file system.

如果 Path 仅由一个名称元素组成,则该路径被视为空路径empty。使用empty path is equivalent to accessing the default directory文件系统的访问文件。



Why Paths.get("").toAbsolutePath()works

为什么Paths.get("").toAbsolutePath()有效

When an empty string is passed to the Paths.get(""), the returned Pathobject contains empty path. But when we call Path.toAbsolutePath(), it checks whether path length is greater than zero, otherwise it uses user.dirsystem property and return the current path.

将空字符串传递给 时Paths.get(""),返回的Path对象包含空路径。但是当我们调用时Path.toAbsolutePath(),它检查路径长度是否大于零,否则它使用user.dir系统属性并返回当前路径。

Here is the code for Unix file system implementation: UnixPath.toAbsolutePath()

下面是 Unix 文件系统实现的代码:UnixPath.toAbsolutePath()



Basically you need to create the Pathinstance again once you resolve the current directory path.

基本上,您需要在Path解析当前目录路径后再次创建实例。

Also I would suggest using File.separatorCharfor platform independent code.

另外我建议使用File.separatorChar平台独立代码。

Path currentRelativePath = Paths.get("");
Path currentDir = currentRelativePath.toAbsolutePath(); // <-- Get the Path and use resolve on it.
String filename = "data" + File.separatorChar + "foo.txt";
Path filepath = currentDir.resolve(filename);

// "data/foo.txt"
System.out.println(filepath);

Output:

输出:

/Users/user/coding/data/foo.txt

回答by CoderCroc

Paths#get(String first, String... more)states,

Paths#get(String first, String... more)状态,

Converts a path string, or a sequence of stringsthat when joined form a path string, to a Path.

...

A Pathrepresenting an emptypath is returned if first is the empty string and more does not contain any non-empty strings.

将路径字符串或连接形成路径字符串的字符串序列转换为Path.

...

如果 first 是空字符串并且 more 不包含任何非空字符串,则返回Path表示路径的A 。

To get the current user directory you can simply use System.getProperty("user.dir").

要获取当前用户目录,您只需使用System.getProperty("user.dir").

Path path = Paths.get(System.getProperty("user.dir"), "abc.txt");
System.out.println(path);

Moreover, getmethod uses variable length argumentof String, which will be used to provide subsequent path strings. So, to create Pathfor /test/inside/abc.txtyou have to use it in a following way,

此外,get方法使用可变长度的参数String,其将被用于提供后续的路径串。因此,要Path/test/inside/abc.txt您创建必须以以下方式使用它,

Path path = Paths.get("/test", "inside", "abc.txt");

回答by Rober2D2

Not an specific method.

不是具体的方法。

If you use java 8 or better, you have 2 options:

如果您使用 java 8 或更高版本,则有 2 个选项:

a) Use java.util.StringJoiner

a) 使用 java.util.StringJoiner

StringJoiner joiner = new StringJoiner(File.pathSeparator); //Separator
joiner.add("path1").add("path2");
String joinedString = joiner.toString();

b) Use String.join(File.pathSeparator, "path1", "path2");

b) 使用 String.join(File.pathSeparator, "path1", "path2");

If you use java 7 or lower, you may use commons-lang library from apache commons. The class StringUtils has a method to join strings using a separator.

如果您使用 java 7 或更低版本,则可以使用来自 apache commons 的 commons-lang 库。StringUtils 类有一个使用分隔符连接字符串的方法。

c) StringUtils.join(new Object[] {"path1", "path2"}, File.pathSeparator);

C) StringUtils.join(new Object[] {"path1", "path2"}, File.pathSeparator);

A sidenote: You may use linux pathseparator "/" for windows (Just remember that absolute paths are something like "/C:/mydir1/mydir2". Using always "/" is very useful if you use protocols such as file://

旁注:您可以在 Windows 中使用 linux 路径分隔符“/”(请记住,绝对路径类似于“/C:/mydir1/mydir2”。如果您使用诸如 file:// 之类的协议,始终使用“/”非常有用

回答by VGR

The most basic way is:

最基本的方法是:

Path filepath = Paths.get("foo", "bar");

You should never write Paths.get(""). I'm surprised that works at all. If you want to refer to the current directory explicitly, use Paths.get(System.getProperty("user.dir")). If you want the user's home directory, use Paths.get(System.getProperty("user.home")).

你永远不应该写Paths.get(""). 我很惊讶这有效。如果要明确引用当前目录,请使用Paths.get(System.getProperty("user.dir")). 如果您想要用户的主目录,请使用Paths.get(System.getProperty("user.home")).

You can also combine the approaches:

您还可以结合使用以下方法:

Path filepath = Paths.get(
    System.getProperty("user.home"), "data", "foo.txt");

回答by Patrick Parker

The most reliable, platform-independent way to join paths in Java is by using Path::resolve(as noted in the JavaDoc for Paths::get). For an arbitrary-length array of Strings representing pieces of a path, these could be joined together using a Java Stream:

在 Java 中连接路径的最可靠、与平台无关的方法是使用Path::resolve(如 JavaDoc for 中所述Paths::get)。对于表示路径片段的任意长度字符串数组,可以使用 Java Stream 将它们连接在一起:

private static final String[] pieces = {
    System.getProperty("user.dir"),
    "data",
    "foo.txt"};
public static void main (String[] args) {
    Path dest = Arrays.stream(pieces).reduce(
    /* identity    */ Paths.get(""),
    /* accumulator */ Path::resolve,
    /* combiner    */ Path::resolve);
    System.out.println(dest);
}

回答by Robin Mathur

You can do like

你可以像

// /root
Path rootPath = Paths.get("/root");
// /root/temp
Path temPath = rootPath.resolve("temp");

A good detailed post is here Path Sample Usecase

一个很好的详细帖子在这里路径示例用例