Pawan
Pawan

Reputation: 443

How do I use a properties file in Java?

In the web application, which I am going to build, I need some SQL queries, which I can store in a properties file, and get them into my Java code, and then execute.

I have found many suggestions on the internet, but nothing helped me. Some of them are

this.getClass().getClassLoader().getResourceAsStream("resources/file.properties");
this.getClass().getResourceAsStream("resources/file.properties");

I have kept the properties file in resources, and in the same directory in which my Java file is present. Nothing worked. I am using Eclipse and Struts2.

Upvotes: 1

Views: 90

Answers (1)

meskobalazs
meskobalazs

Reputation: 16041

Make sure that your properties files goes to WEB-INF\classes, where your struts.xml is. This folder is on the classpath. Then

this.getClass().getClassLoader().getResourceAsStream("file.properties");

should work as expected. Or of course, if you create a resources folder in classes, the aforementioned code should work too.

If by resources folder you mean src/main/resources, then it is managed by Maven, and it is copied directly to WEB-INF/classes. So you do not need to specify the resorces folder in the method.

Upvotes: 3

Related Questions