hthomos
hthomos

Reputation: 297

Have Relative Paths as properties in property file

So my question is NOT how to load properties file from relative path, but rather how can I declare relative paths (relative to the properties file) as properties path in the file?

For example, I want to have a directory etc.

|-etc
|---File1
|---File2
|---properties.

Now inside properties I want something like,

file1 = ./File1
file2 = ./File2

but Java will simply get the actual content like "./File1"

How can i wire it so that Java will get the property and understand it should be relative to where the properties file is?

So when you do new File(properties.getproperty(file1)) it will will try to look for the file in C://etc/File1 rather than just ./File1

Upvotes: 2

Views: 5307

Answers (2)

Master Slave
Master Slave

Reputation: 28569

To complement Jon's answer, you'll have to somehow set the root folder as reference point. Your line

new File(properties.getproperty(file1))

will look for a relative path comparing to the location of the .class file of the compiled Java class that holds the line. Even if you properly set the relative path with respect to this, if you were to move the class one package up, the code would break.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503489

You need to understand that Java properties files are just lists of key/value pairs. How you interpret those values is up to you. So you should expect that properties.getProperty("file1") will give you the string "./File1"... but you can use that as a relative filename very easily:

File rootDirectory = ...; // However you get this
String relativePath = properties.getProperty("file1");
File file = new File(rootDirectory, relativePath);

Upvotes: 1

Related Questions