Where to put a properties file in Java?
Asked Answered
G

4

12

I tried to read a .properties file in Java and have the following code:

public final class Config  {
    static {
        Properties properties = new Properties();
        InputStream propertiesStream = Object.class.getResourceAsStream("config.properties");

        if (propertiesStream != null) {
            try {
                properties.load(propertiesStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("file not found");
        }
    }
}

But it keeps saying file not found.

The content of properties is

pwd=passw0rd

Anyone knows how to solve this problem?

Goddamned answered 29/5, 2013 at 5:52 Comment(0)
E
23

It should be in classpath, put it to your root source package, if its a maven project put it to src/main/resources directory

Elisabeth answered 29/5, 2013 at 5:54 Comment(1)
But then changes will require compile. What if we put on fixed path instead? But the drawback will be error if path was not found. Which is better?Koodoo
T
0

it should be in WebContent/Web-Inf/ folder

and in you xml file define the bean like this :

<bean id="propertyConfigurer" class="com.your.project.util.properties.ApplicationProperties">
    <property name="locations">
        <list>
            <value>/WEB-INF/application.properties</value>
        </list>
    </property>
</bean>
Trudeau answered 29/5, 2013 at 5:59 Comment(3)
if the framework you are using is Spring, then this would work fineTrudeau
Did the OP said he is using spring.?Gotcher
I realized that later and I put a comment (before yours) already for the same reason, adding the disclaimer. It might be helpful for a person who stumbles upon this question while working with Spring and facing this same issue.Trudeau
B
-1

You could also keep config.properties in the same folder as Config.java.

//InputStream propertiesStream = Object.class.getResourceAsStream("config.properties");
InputStream propertiesStream   = Config.class.getResourceAsStream("config.properties");
Briannebriano answered 29/5, 2013 at 6:13 Comment(0)
E
-1

You can have two choices of selecting the path,

  1. Open the file containing folder and get the path and save that path in the string with file like,

    InputStream propertiesStream = Object.class.getResourceAsStream(path + File.seperator + "config.properties");

  2. Save the file in src path,

    WorkSpace -> Project Name -> Copyhere

Eventuality answered 29/5, 2013 at 6:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.