Java中的连接路径


99

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

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

我想才达到在Java中一样,不用担心,如果OSUnixSolarisWindows

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

}

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


1
这可能是我没看到的东西。您当前的路径是“”。您的第二个路径是“ data / foo.txt”。也许您的问题是您似乎正在打印Path对象而不是filepath.toString()
cjds 2015年

2
使用new File(parent, child)
saka1029

Answers:


99

即使使用该方法获得当前目录的原始解决方案也是如此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());

输出:

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

从Java Path类文档中:

如果Path仅由一个name元素组成,则将其视为空路径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);

输出:

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

不是我,也许有人认为在字符串上工作并且separatorChar不如“更高层次的抽象”,看起来像PathBuilder(currentRelativePath).append("data").append("foo.txt")
jingyu9575,2015年

22

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

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

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

11

没有特定的方法。

如果使用Java 8或更高版本,则有2种选择:

a)使用java.util.StringJoiner

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

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

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

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

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


StringJoiner返回了我/home/user/test:foo.txt
cybertextron

您所知道的选项并不是唯一存在的选项。例如,可以使用StringBuilder代替Joiner。实际上,基于字符串而不是文件/路径的实现非常幼稚,并且会在许多情况下导致问题。
XenoRo 2015年

2
File.separator为我工作,而不是File.pathSeparator
Evan Siroky,

使用Pathes.get(“ path1”,“ path2”)。toAbsolutePath()。toString()
Erdinc Ay

5

最基本的方法是:

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

你永远不应该写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");

1

在Java中,最可靠,独立于平台的联接路径的方法是使用Path::resolve(如JavaDoc中所述Paths::get)。对于表示路径段的任意长度的String数组,可以使用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 using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.