I have a configuration file which holds several file paths.
If these paths are relative, I want them to be relative to the path of the configuration file (and not to the path of the user working directory ("user.dir")).
Since it's not possible to change the working directory with Java, I've written this method:
public static File newFile(String parent, String child) {
File file = new File(child);
if(file.isAbsolute()) {
return file;
}
return new File(parent, child);
}
The folder of my config file would be parent here.
Is there a better solution than this?
1 Answer 1
A very raw and simple approach. I believe you would be loading the properties from the configuration file.
Properties prop = new Properties();
prop.load(new FileInputStream("somepath/config.properties"));
Hence I assume you know the path of your config file.
Now simple iterate over your properties and set them again.
for(String name : getProperty.getNames()) {
String propValue = prop.getProperty(name);
//TODO if(propValue == relative)
setProperty(name, somepath + propValue);
}
-
2\$\begingroup\$ How is this any better than the code in the question? \$\endgroup\$janos– janos2015年02月22日 08:42:00 +00:00Commented Feb 22, 2015 at 8:42
-
\$\begingroup\$ Thanks for your comment, I am presenting another approach to his problem, perhaps a simpler one. \$\endgroup\$Milind J– Milind J2015年02月22日 23:19:08 +00:00Commented Feb 22, 2015 at 23:19
-
\$\begingroup\$ Thanks. I'm using a XML config file which I readout with own methods. I don't think simple concatenation of the paths is a better way. \$\endgroup\$halloei– halloei2015年02月27日 08:50:13 +00:00Commented Feb 27, 2015 at 8:50
relativize()would force every path to be relative to my configuration file. That's not what I need. Furthermore, this won't work if both paths are of different types or on different roots. \$\endgroup\$parentorchild? \$\endgroup\$parentin my method \$\endgroup\$