Where should the file for getClassLoader () be located.getResourceAsStream?

Hello.

There was a need to put information about DB connections in a separate file. I tried to use this option, BUT I still can't understand where the file db.properties{[4] 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 does not find it. I tried to specify an absolute path - the result is also negative.

Where should it be?

Author: Nikolay Baranenko, 2016-07-28

1 answers

Example 1. using the construction getClass().getResource("/images/logo.png"). Since the name starts with the ' / ' character, it is considered absolute. The resource search is performed as follows:

The path from classpath c:\work\myproject\classes is assigned the resource name /images/logo.png, resulting in a search for the file c:\work\myproject\classes\images\logo.png. If the file is found, the search stops. Otherwise: In the jar file c:\lib\lib.jar, the file /images/logo.png is searched, and the search is conducted from the root of the jar file.

Example 2. We use the construction getClass().getResource("res/data.txt"). Since the name does not start with the ' / ' character, it is it is considered relative. The resource search is performed as follows:

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

In your case, you need to write getResourceAsStream("db.properties") without specifying the ' / ' character, so that the file found in the folder project\src\main\resources\ but you can put db.properties in project\db.properties and already specify as in your example

 8
Author: Senior Pomidor, 2016-07-28 07:59:09