6
\$\begingroup\$

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?

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Maybe you are looking for docs.oracle.com/javase/7/docs/api/java/nio/file/… \$\endgroup\$
    – Grim
    Jan 13, 2015 at 12:47
  • \$\begingroup\$ Sorry, I'm using Java 6. But 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\$
    – halloei
    Jan 13, 2015 at 13:04
  • \$\begingroup\$ I think about: if its relative, absolutize to jvm, relativize to config again. What is the config? parent or child? \$\endgroup\$
    – Grim
    Jan 13, 2015 at 13:16
  • 2
    \$\begingroup\$ The folder of my config file would be parent in my method \$\endgroup\$
    – halloei
    Jan 13, 2015 at 13:17

1 Answer 1

2
\$\begingroup\$

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);
}
\$\endgroup\$
3
  • 2
    \$\begingroup\$ How is this any better than the code in the question? \$\endgroup\$
    – janos
    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
    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
    Feb 27, 2015 at 8:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.