Reprinted from http://blog.163.com/wb_zhaoyuwei/blog/static/183075439201261764454791/
When our own programs need to process a configuration file (such as an XML file or a properties file), you typically encounter two problems:
(1) Where should my configuration file be placed?
(2) How does my profile find it?
For the first question, the answer is: Please put your resource file in Classpath, if the resource file is in the jar, add the jar file to Classpath.
For the second question, it depends on which class (class or ClassLoader) you are using to load the resource file, so let's discuss the loading mechanism of the class and ClassLoader classes for the resource file.
(a) Loading resource files with class classes
Load the resource file by calling the class getResourceAsStream method:
Often used more is the JdbcUtil.class.getResourcrAsStream ("/database.properties");
Public InputStream getResourceAsStream (String pathtoconfigfile);
The method receives a string parameter (Pathtoconfigfile) to represent the address of the resource file, returns the input stream (InputStream) of the resource file if it is successfully loaded, and returns null if it fails.
It is important that there are two ways to pass in the Pathtoconfigfile parameter,
The first way is absolute positioning, that is, pathtoconfigfile with "/", at this time Java classpath as the root directory, directly add Pathtoconfigfile to search for resource files.
The second way is relative positioning, that is, Pathtoconfigfile does not start with "/", the full path of the resource file should be: The package path of the class that calls the getResourceAsStream method plus pathtoconfigfile. ("." When the package is converted to a catalog.) Become "/")
(ii) Loading resource files with the ClassLoader class
The ClassLoader class also provides the same loading method as class classes:
Public InputStream getResourceAsStream (String pathtoconfigfile);
When loading a configuration file with ClassLoader, Pathtoconfigfile cannot begin with "/" and can be found directly under classpath when looking. The class class, when looking for a resource file, is also a proxy (delegate) for ClassLoader to complete the lookup function, please refer to the Java official 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");
Java Load configuration file