1
votes

I m trying to load properties file to create a configuration. namely foo.properties.

What the best place to store this config file. Within the package where i will use initialize the using class? on the root level of the src?

Also, while accessing the files, i am using the location of the file in the file system: ie: c:\configs\foo.properties.

Is there a better practice for this? such as using the path relative to the project rather than the file system location? if yes, how can i reference the location of a property file within a project tree. such as:

src/
   /com.foo.bar
   /com.foo.car
   /com.foo.zar
   foo.properties

lets say i want to read the properties file to memory, how do i access this foo.properties without using the OS location/ or the location in the file system.

3
Answers to your questions are heavily dependent on what kind of app you're talking about, how it will be started, and what kind of configuration you're talking about.Ryan Stewart

3 Answers

2
votes

The way that I've always seen it done is to place the properties file in src/main/resources and then access it with getResourceAsStream().

This would be a good question to look at: Load a resource contained in a jar

1
votes

If you want keep something close to your current structure then you can just add a resources folder, like so:

src/
   /com.foo.bar
   /com.foo.car
   /com.foo.zar
resources
   /foo.properties

But I highly recommend following Maven directory structures, they really do give you a lot of flexibility:

src/
    /main
        /java
            /com.foo.bar
            /com.foo.car
            /com.foo.zar
        /resources
            /foo.properties

Regardless of what layout you go with I would recommend putting your resources in a folder structure matching one of your Java packages, that way you can easily load them as resources, avoiding your absolute vs relative file path conundrum. Something like this:

src/
    /resources/
       /com/foo/bar/foo.properties

And given a class com.foo.bar.MyClass you can do something like this:

InputStream is = MyClass. getResourceAsStream("com/foo/bar/foo.properties");
0
votes

I think the location really depends on your project. I usually like having a specific folder to store configuration files.

As to the way you access the file, using absolute paths is a really bad ideia: Imagine you want to distribute your application as a Jar, deploy it on a web server, or simply move it to another place completly!

Take a look at:

http://docs.oracle.com/javase/8/docs/api/java/lang/ClassLoader.html#getResourceAsStream-java.lang.String-

If you have the properties file in your classpath (as part of your source, for instance), then you can load it in the same way independently of where you are (even inside a jar).