Search code examples
javaconfigurationpathconfiguration-files

Best practices to work with file paths in Java


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.


Solution

  • 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");