tags:

views:

98

answers:

2

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?

+2  A: 

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
Fabian Steeg
But the absolute path can have ..'s in it if I do that. I don't want those. Is there a way to get rid of them from the resulting absolute path?
Tom Tresansky
@Tom: Using `getCanonicalPath()` instead of `getAbsolutePath()` is probably what you're looking for, in that case.
Tim Stone
@Tim Thanks, updated the answer.
Fabian Steeg
A: 

I know it isn't the best solution but can't you just combine the substring of fileA's path from 0 to the lastIndexOf("\") with fileB's path.

Example A:

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

Example Bs:

  • ....\module3\submodule9\subsubmodule32\fileB

    C:\projects\project1\module7\submodule5 \ .. \ ..\module3\submodule9\subsubmodule32\fileB

If you don't want the .. in there then, it would take longer, but I recommend going through the path for fileB and keep taking the substring from 0 to the first index of \. Then check the substring. If it is .. then remove the substring from there and remove the substring from fileA's path from lastIndexOf(\) to length. Then repeat. That way you are removing the folders you don't need and the ..s.

So :

Example A:

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

Example Bs:

  • ....\module3\submodule9\subsubmodule32\fileB

    --> C:\projects\project1\module3\submodule9\subsubmodule32\fileB

Kyra
I should clarify, I want the simplest form of the path to B.
Tom Tresansky