Tom Tresansky Tom Tresansky - 4 months ago 22
Java Question

Converting Relative Paths to Absolute Paths

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?


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