简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM