0

I am trying to access the config.properties file which was previously placed in the config folder. after some research, I moved it to the WEB-INF folder. but even after I moved it, it still return java.lang.NullPointerException whenenver I run my my program. code used to store some password information as below:

         ClassLoader resource = ConnectionManager.class.getClass().getClassLoader();
         URL path = ConnectionManager.class.getClass().getResource("/WEB-INF/config.properties");
         
         props.load(new FileInputStream(path.getFile()));
    
         String passwordds = props.getProperty("datasource.password");

these are the codes that I found and I try to use it but still I got the null exception.

I cannot use absolute path due to this project will be deploy to production server as in .war file. please advise what is the best way as I am still beginner.

sharky
  • 196
  • 1
  • 1
  • 14
  • can you be more specific like what type of project is it j2ee or spring? .you can place it in any package and this might be very helpful https://stackoverflow.com/questions/4361338/reading-txt-file-from-a-specific-package-java – Richard Elite Jan 13 '21 at 02:48
  • @ManojKrishna it is javaee. I have tried your suggestion but it still failed. i tried this code line: File f = new File(ConnectionManager.class.getResource("/config.properties").getFile()); props.load(new FileInputStream(f.getAbsoluteFile())); – sharky Jan 13 '21 at 03:24

1 Answers1

0

You should check the war your build tool generated, and find where your config file really are.

For maven project, the default resource dir is /src/main/resources/

So /src/main/resources/config.properties will be put at /WEB-INF/classes/config.properties in a war.

You can use getClass().getResourceStream("/config.properties") (getResource sometimes not work will in j2ee environment) to get it.

vipcxj
  • 840
  • 5
  • 10
  • right now I am running on my localhost which previously I was using the absolute path. but then i noticed this issue when i deploy to LAN server. of coz the absolute path is the main issue since system cannot read the path that map to my local path. now my idea is to change it to relative path instead. not sure how to do since i never do this before. – sharky Jan 13 '21 at 03:35
  • @sharky In your case, you can use getResourceStream directly. The path retun from getResource sometimes not work in complex j2ee environment. On the other hand, in rare case the class loader my be problom, try to use the class loader of the class which packaged in the same war of you config file. – vipcxj Jan 13 '21 at 04:02