0

I am writing a simple JSF application and am trying to get a resource (database.properties file) using Class, ClassLoader, and URL that is not working. url is null and I don't know why. I have done a lot of research but without success.

Code:

Class cls = Class.forName("<packagename>.SimpleDataSource");
ClassLoader cLoader = cls.getClassLoader();
URL url = cLoader.getResource(fileName); // fileName = "database.properties"  w/o the double quote
FileInputStream in = new FileInputStream(url.getFile()); 
Sandeep Chatterjee
  • 3,220
  • 9
  • 31
  • 47
mitchj
  • 623
  • 4
  • 9
  • 16

2 Answers2

0

Thanks for your comment Sandeep, it was helpful. I found out that my properties file was in the wrong place. I then moved it inside my src folder under the java resources folder and now my properties file gets loaded in. I have a new problem now but will start a new thread if I can't figure it out.

mitchj
  • 623
  • 4
  • 9
  • 16
0

Once you have a URL you can get an InputStream from it using url.openStream(), or you can simply use cLoader.getResourceAsStream(...) in the first place. Your current approach of

FileInputStream in = new FileInputStream(url.getFile());

will work on some platforms but not all, and only when your application is running from a directory on disk. It will fail if your classes and resources are packed up into a JAR, but if you use getResourceAsStream it will work from a JAR as well as an unpacked directory.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183