How to get a clean absolute file path in Java regardless of OS?

30,391

Solution 1

Try with this:

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("myFile.txt");
        Path absolutePath = path.toAbsolutePath();

        System.out.println(absolutePath.toString());
    }
}

Solution 2

You can use:

Path absolutePath = path.toAbsolutePath().normalize();

... at least to eliminate the redundant relative sections. As the documentation for normalize() mentions, in case that an eliminated node of the path was actually a link, then the resolved file may be different, or no longer be resolvable.

Share:
30,391

Related videos on Youtube

Actine
Author by

Actine

Updated on October 10, 2020

Comments

  • Actine
    Actine over 3 years

    Here's the problem. After some concatenations I may happen to have a string like this

    "C:/shared_resources/samples\\import_packages\\catalog.zip"
    

    or even this

    "C:/shared_resources/samples/subfolder/..\\import_packages\\catalog.zip"
    

    I want to have some code that will convert such string into a path with uniform separators.

    The first solution that comes to mind is using new File(srcPath).getCanonicalPath(), however here's the tricky part. This method relies on the system where the tests are invoked. However I need to pass the string to a remote machine (Selenium Grid node with a browser there), and the systems here and there are Linux and Windows respectively. Therefore trying to do new File("C:/shared_resources/samples\\import_packages\\catalog.zip").getCanonicalPath() results in something like "/home/username/ourproject/C:/shared_resources/samples/import_packages/catalog.zip". And using blunt regex replacement doesn't seem a very good solution too.

    Is there a way just to prune the path and make delimiters uniform (and possibly resolving ..'s) without trying to implicitly absolutize it?

    • Andrew Thompson
      Andrew Thompson about 11 years
      Try something like.. File f = new File("C:/shared_resources/samples\\import_packages\\catalog.‌​zip"); System.out.println(f.toURI().toURL());
  • koppor
    koppor over 6 years
    This leaves a . in there: . gets D:\git-repositories\winery\winery\. instead of D:\git-repositories\winery\winery. Adding normalize() at the end also removes the final ..
  • stippi
    stippi over 4 years
    toAbsolutePath() does not eliminate redundant relative sections.