Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Relative Paths to Absolute Paths

Tags:

java

path

I have an absolute path to file A.

I have a relative path to file B from file A's directory. This path may and will use ".." to go up the directory structure in arbitrarily complex ways.

Example A:

  • C:\projects\project1\module7\submodule5\fileA

Example Bs:

  • ..\..\module3\submodule9\subsubmodule32\fileB
  • ..\submodule5\fileB
  • ..\..\module7\..\module4\submodule1\fileB
  • fileB

How do I combine the two in order to get the simplest possible absolute path to file B?

like image 706
Tom Tresansky Avatar asked Jul 08 '10 15:07

Tom Tresansky


People also ask

How do you convert relative path to absolute path in Python?

Use abspath() to Get the Absolute Path in Python abspath() with the given path to get the absolute path. The output of the abspath() function will return a string value of the absolute path relative to the current working directory.

Can an absolute path be a relative path?

An absolute path is a path that describes the location of a file or folder regardless of the current working directory; in fact, it is relative to the root directory.

How do you find the absolute path of a shell?

In this case, first, we need the current script's path, and from it, we use dirname to get the directory path of the script file. Once we have that, we cd into the folder and print the working directory. To get the full or absolute path, we attach the basename of the script file to the directory path or $DIR_PATH.

How is a relative path different from an absolute path?

An absolute path is defined as specifying the location of a file or directory from the root directory(/). In other words,we can say that an absolute path is a complete path from start of actual file system from / directory. Relative path is defined as the path related to the present working directly(pwd).


2 Answers

If I get your problem right, you could do something like this:

File a = new File("/some/abs/path"); File parentFolder = new File(a.getParent()); File b = new File(parentFolder, "../some/relative/path"); String absolute = b.getCanonicalPath(); // may throw IOException 
like image 86
Fabian Steeg Avatar answered Sep 28 '22 21:09

Fabian Steeg


String absolutePath = FileSystems.getDefault().getPath(mayBeRelativePath).normalize().toAbsolutePath().toString(); 
like image 40
rssdev10 Avatar answered Sep 28 '22 22:09

rssdev10