Where to put properties file in eclipse and how to access the path both locally and on server

StackOverflow https://stackoverflow.com/questions/23639403

  •  21-07-2023
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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");

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top