Where to put properties file in eclipse and how to

2020-07-22 17:21发布

问题:

I saw some similar questions on this,but I don't understand them enough so i want to ask the question and tailor it my own way.

I have a properties file that I store in src/main/resources, and then reference this in my code like so:

    Properties prop = new Properties();
    InputStream input = null;

    try { 
        input = new FileInputStream("src/main/resources/app.properties");

        // load a properties file
        prop.load(input);

this works locally, however when I create a .war file and deploy it to the sever it has no idea where the properties file is. Where do I put this properties file, and how do I reference it in the code, so that I can run it locally, and on the server without any problems?

回答1:

I assume you have maven project, you can put that properties file at src/main/resources/app.properties and change the code to read it as

getClass().getClassLoader().getResourceAsStream("/app.properties");


回答2:

It seems that you are using maven project so files which are define in /src/main/resources/
is directly available in classpath. Like /src/main/resources/app.properties is on classpath as classpath: app.properties.



回答3:

From the architecture I see, I guess you're using Maven. So your property file will be located in you {warFile}/WEB-INF/classes. To access such a file at runtime, use the following code :

input = new FileInputStream(getClass().getClassLoader().getResourceAsStream("/app.properties"));

This is because all that is located in WEB-INF/classes is "in your classpath". In order to access your classpath, you must get the related classloader. The best way to do that, is from a class in the same WAR.