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?

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
CSLearner
  • 121
  • 1
  • 1
  • 4

4 Answers4

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

jmj
  • 237,923
  • 42
  • 401
  • 438
  • 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? – stuckedunderflow May 21 '19 at 08:54
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>
Mitaksh Gupta
  • 1,029
  • 6
  • 24
  • 50
-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");
krishnakumarp
  • 8,967
  • 3
  • 49
  • 55
-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

Gowthami Reddy
  • 430
  • 7
  • 23