Joining paths in Java

后端 未结 6 1248
有刺的猬
有刺的猬 2021-01-30 02:48

In Python I can join two paths with os.path.join:

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

I\'m trying to

6条回答
  •  旧巷少年郎
    2021-01-30 03:24

    Even though the original solution for getting the current directory using the empty String works. But is recommended to use the user.dir property for current directory and user.home for home directory.

    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 Path class Documentation:

    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 directory of the file system.


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

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

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


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

    Also I would suggest using File.separatorChar for platform independent code.

    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
    

提交回复
热议问题