Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 375
Actine Avatar asked Apr 19 '13 11:04

Actine


People also ask

How do you create an absolute path in Java?

io. File. getAbsolutePath() is used to obtain the absolute path of a file in the form of a string. This method requires no parameters.

How do I find the absolute path of a file?

The getAbsolutePath() method is a part of File class. This function returns the absolute pathname of the given file object. If the pathname of the file object is absolute then it simply returns the path of the current file object.

What is canonical path in Java?

The canonical path is always an absolute and unique path. If String pathname is used to create a file object, it simply returns the pathname. This method first converts this pathname to absolute form if needed. To do that it will invoke the getAbsolutePath() Method and then maps it to its unique form.

How do you get the path of the file in the file Java?

In Java, for NIO Path, we can use path. toAbsolutePath() to get the file path; For legacy IO File, we can use file. getAbsolutePath() to get the file path.


1 Answers

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());     } } 
like image 126
Dragan Menoski Avatar answered Oct 06 '22 04:10

Dragan Menoski