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

4

27

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?

Unspent answered 19/4, 2013 at 11:58 Comment(1)
Try something like.. File f = new File("C:/shared_resources/samples\\import_packages\\catalog.zip"); System.out.println(f.toURI().toURL());Dissuade
L
31

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());
    }
}
Lothaire answered 19/4, 2013 at 18:4 Comment(2)
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 ..Gwyngwyneth
toAbsolutePath() does not eliminate redundant relative sections.Rosalvarosalyn
R
7

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.

Rosalvarosalyn answered 9/10, 2019 at 10:26 Comment(1)
This helped me to remove the /../ (Access to upper directory) and get a more "clean" absolute path.Jeanninejeans
C
0

Try FilenameUtils.normalize() from Apache commons-io

Crossfertilize answered 7/9, 2013 at 19:44 Comment(0)
R
-4

for example here is your path:

String jarName = "C:/shared_resources/samples\\import_packages\\catalog.zip"
jarName.replaceAll("/", "\\");
jarName.replaceAll("..", "/");
Restivo answered 19/4, 2013 at 14:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.