在 Java 中连接路径

2022-08-31 08:08:14

在我可以连接两个路径与:Pythonos.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

即使原始解决方案使用当前目录的工作原理。但建议将该属性用于当前目录和主目录。empty Stringuser.diruser.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 元素组成,则该路径被视为空路径。使用 文件系统 的 访问文件。emptyempty path is equivalent to accessing the default directory


Why Paths.get(“”).toAbsolutePath() works

当一个空字符串被传递给 时,返回的对象包含空路径。但是当我们调用 时,它会检查路径长度是否大于零,否则它使用系统属性并返回当前路径。Paths.get("")PathPath.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

答案 2

Paths#get(字符串优先,字符串优先...更多)状态,

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

...

如果第一个是字符串,并且更多不包含任何非空字符串,则返回表示空路径的 Path

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

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

此外,方法使用 可变长度参数 ,该参数将用于提供后续路径字符串。因此,要为您创建,您必须通过以下方式使用它,getStringPath/test/inside/abc.txt

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

推荐