Leander Leander - 8 months ago 39
Java Question

Java parse File-path with different working directory

I have a file which contain several paths, like

(relative) or
(absolut). I need to parse the paths that are relative to the directory of the file that contains the paths and not the working-directory and create correct File-instances. I can not change the working directory of the Java-Program, since this would alter the behaviour of other components and i also have to parse several files. I don't think
public File(String parent, String child)
does what i want, but i may be wrong. The documentation is quite confusing.


file xy located under /system/exampleProgram/config.config has the following content:

i want to resolve these to:


So, I am going to assume that you have access to the path of the file you opened (either via File.getAbsolutePath() if it was a File descriptor or via a regex or something)...

Then to translate your relative paths into absolute paths, you can create new File descriptions with your opened file, like so:

File f = new File(myOpenedFilePath);
File g = new File(f, "./extensions");
String absolutePath = g.getCanonicalPath();

When you create a file with a File object and a String, Java treats the String as a path relative to the File given as a first argument. getCanonicalPath will get rid of all the redundant . and .. and such.

Edit: as Leander explained in the comments, the best way to determine whether the path is relative or not (and thus whether it should be transformed or not) is to use file.isAbsolute().