HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Make file paths relative to the configuration file path

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pathfilethemakepathsconfigurationrelative

Problem

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?

Solution

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);
}

Code Snippets

Properties prop = new Properties();
prop.load(new FileInputStream("somepath/config.properties"));
for(String name : getProperty.getNames()) {
   String propValue = prop.getProperty(name);
   //TODO if(propValue == relative)
   setProperty(name, somepath + propValue);
}

Context

StackExchange Code Review Q#77398, answer score: 2

Revisions (0)

No revisions yet.