Java load the configuration file, java configuration file
Reprinted from http://blog.163.com/wb_zhaoyuwei/blog/static/183075439201261764454791/
When our own program needs to process configuration files (such as xml files or properties files), we usually encounter two problems:
(1) Where should I put my configuration file?
(2) Why can't I find my configuration file?
For the first question, the answer is: Put your resource file in classpath. If the resource file is in jar, add the jar file to classpath.
For the second question, you must check which Class (Class or ClassLoader) You are using to load the resource file, so next we will discuss the loading mechanisms of resource files for the Class and ClassLoader Class respectively.
(1) Use the Class to load resource files
Call the getResourceAsStream method of the Class to load the resource file:
JdbcUtil. class. getResourcrAsStream ("/database. properties") is usually used ");
Public InputStream getResourceAsStream (String pathToConfigFile );
This method receives a String-type parameter (pathToConfigFile) to indicate the address of the resource file. If the load is successful, the input stream (InputStream) of the resource file is returned. If the load fails, null is returned.
It is important that there are two ways to pass in the pathToConfigFile parameter,
The first method is absolute positioning, that is, pathToConfigFile starts with "/". In this case, Java uses classpath as the root directory and directly adds pathToConfigFile to search for resource files.
The second method is relative positioning, that is, pathToConfigFile does not start with "/". the full path of the resource file should be: package path of the class that calls the getResourceAsStream method plus pathToConfigFile. (Change "." to "/" when converting a package into a directory "/")
(2) Use the ClassLoader class to load resource files
The ClassLoader Class also provides the same loading method as the Class:
Public InputStream getResourceAsStream (String pathToConfigFile );
When you use ClassLoader to load a configuration file, pathToConfigFile cannot start with "/". You can directly search for it under classpath. When searching for resource files, the Class is also a proxy (delegate) for ClassLoader to complete the search function, please refer to the official Java documentation.
InputStream input = this.getClass().getClassLoader().getResourceAsStream("resources/config.properties");
InputStream input = ClassLoader.getSystemResourceAsStream("resources/config.properties");
InputStream input = ClassLoader.getSystemClassLoader().getResourceAsStream("resources/config.properties");