Hello.

There was a need to make information about database connections in a separate file. I tried to use this option, but I still can not understand where the file db.properties should physically lie

 Properties prop = new Properties ();
 InputStream inputStream = FetchData.class.getClassLoader (). GetResourceAsStream ("/ db.properties");
 prop.load (inputStream);
 String driver = prop.getProperty ("driver");
 String url = prop.getProperty ("url");
 String user = prop.getProperty ("user");
 String password = prop.getProperty ("password");

Tried to place /web-inf/classes/db.properties not found. I tried to specify the absolute path - the result is also negative.

Where should he be?

  • Maven? Put your file in src \ main \ resources \ - Chubatiy
  • and remove / out of the way (ie. ship as FetchData.class.getClassLoader().getResourceAsStream("db.properties") ) - Chubatiy
  • The collector is not a maven project in IDEA. I tried 2 more options to remove the "/" + copy of the file and put it in the root of the project, it did not work. - Nikolay Baranenko
  • Try to put simply in src and again just call without / . Do you have java.lang.NullPointerException ? - Chubatiy

1 answer 1

Example 1. using the getClass().getResource("/images/logo.png") construct. Since the name starts with the character '/', it is considered absolute. Search for a resource is as follows:

The resource name /images/logo.png assigned to the path from the classpath c:\work\myproject\classes , as a result of which the file c:\work\myproject\classes\images\logo.png is searched. If the file is found, the search is terminated. Otherwise: In the jar file c:\lib\lib.jar the file c:\lib\lib.jar is searched, and the search is conducted from the root of the jar file.

Example 2. We use the getClass().getResource("res/data.txt") construct. Since the name does not begin with the character '/', it is considered relative. Search for a resource is as follows:

The path from the classpath c:\work\myproject\classes assigned the current class package, where the code is located, /ru/skipy/test , and then the resource name res/data.txt , which results in a file c:\work\myproject\classes\ru\skipy\test\res\data.txt . If the file is found, the search is terminated. Otherwise: In the jar file c:\lib\lib.jar the file /ru/skipy/test/res/data.txt (the name of the package of the current class plus the name of the resource) is searched for, and the search is conducted from the root of the jar-file.

In your case, you need to write getResourceAsStream("db.properties") without specifying the '/' symbol to find the file in the project\src\main\resources\ folder, but you can put db.properties in the project\db.properties and specify how in your example

  • I tried this variant: InputStream inputStream = FetchData.class.getResourceAsStream ("/ db.properties"); and without the "/" symbol (( - Nikolay Baranenko