在Java中加入路径

cyb*_*ron 91 java

Python我可以加入两个路​​径os.path.join:

os.path.join("foo", "bar") # => "foo/bar"
Run Code Online (Sandbox Code Playgroud)

我试图在Java中实现同样的目标,而不用担心是否OS存在Unix,Solaris或者Windows:

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);

}
Run Code Online (Sandbox Code Playgroud)

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

You*_*bit 82

即使使用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());
Run Code Online (Sandbox Code Playgroud)

输出:

/Users/user/coding/data/foo.txt
Run Code Online (Sandbox Code Playgroud)

从Java Path类文档:

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


为何Paths.get("").toAbsolutePath()有效

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

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


基本上Path,一旦解析当前目录路径,就需要再次创建实例.

我也建议使用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);
Run Code Online (Sandbox Code Playgroud)

输出:

/Users/user/coding/data/foo.txt
Run Code Online (Sandbox Code Playgroud)

  • 不是我,也许有人认为处理字符串和 `separatorChar` 不如一些“更高级别的抽象”,看起来像 `PathBuilder(currentRelativePath).append("data").append("foo.txt")` (2认同)

Cod*_*roc 18

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

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

...

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

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

Path path = Paths.get(System.getProperty("user.dir"), "abc.txt");
System.out.println(path);
Run Code Online (Sandbox Code Playgroud)

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

Path path = Paths.get("/test", "inside", "abc.txt");
Run Code Online (Sandbox Code Playgroud)


Rob*_*2D2 9

不是一个具体的方法.

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

a)使用java.util.StringJoiner

StringJoiner joiner = new StringJoiner(File.pathSeparator); //Separator
joiner.add("path1").add("path2");
String joinedString = joiner.toString();
Run Code Online (Sandbox Code Playgroud)

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

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

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

旁注:你可以使用linux pathseparator"/"作为windows(请记住,绝对路径类似于"/ C:/ mydir1/mydir2".如果使用诸如file://之类的协议,则使用always"/"非常有用.

  • `File.separator` 为我工作而不是 `File.pathSeparator` (4认同)

小智 7

你可以这样做

// /root
Path rootPath = Paths.get("/root");
// /root/temp
Path temPath = rootPath.resolve("temp");
Run Code Online (Sandbox Code Playgroud)

这里有一篇详细的文章Path Sample Usecase


VGR*_*VGR 5

最基本的方法是:

Path filepath = Paths.get("foo", "bar");
Run Code Online (Sandbox Code Playgroud)

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

您还可以结合使用方法:

Path filepath = Paths.get(
    System.getProperty("user.home"), "data", "foo.txt");
Run Code Online (Sandbox Code Playgroud)


ash*_*bar 5

对于 Java >= 11,现在推荐的方法是使用Path.of而不是Paths.get,如前面的答案所建议的。引用 Java 11文档

建议通过 Path.of 方法获取 Path,而不是通过此类中定义的 get 方法,因为此类可能在未来版本中被弃用。

例如,以下内容将根据操作系统路径分隔符连接“foo”和“bar”:

import java.nio.file.Path;
...

Path fooBar = Path.of("foo", "bar");
Run Code Online (Sandbox Code Playgroud)