Usage of getResourceAsStream in Java (take the path)

1. Usage

The getResourceAsStream in Java has the following types:

  1. Class.getResourceAsStream(String path) : When the path does not start with '/' , the resource is obtained from the package where this class is located by default, and if it starts with '/' , it is obtained from the root of the ClassPath. It just constructs an absolute path through path, and ClassLoader finally obtains resources.
  2. Class.getClassLoader.getResourceAsStream(String path) : The default is to obtain resources from the root of ClassPath. The path cannot start with '/', and finally ClassLoader obtains resources.
  3. ServletContext.getResourceAsStream(String path) : By default, resources are fetched from the root directory of WebAPP. It does not matter whether the path under Tomcat starts with '/' or not. Of course, this is related to the specific container implementation.
  4. The application built-in object under Jsp is an implementation of the above ServletContext.

For example, the project directory is as follows: 

|--project 
     |--src 
         |--com.x
		 	 |--file 
				|--myfile3.xml
		     |--y 
				|--Test.java 
				|--myfile.xml
				|--file 
					|--myfile2.xml
     |--target
         |--com.x
		 	 |--file 
				|--myfile3.xml
		     |--y 		 
				|--Test.class 
				|--myfile.xml
				|--file 
					|--myfile2.xml

The usage of getResourceAsStream is roughly as follows:

First: The file to be loaded and the .class file are in the same directory, for example: there is a class Test.class under com.xy, and a resource file myfile.xml at the same time. Then, the code is as follows:

Test.class.getResourceAsStream("myfile.xml");

Second: The resource file is in the subdirectory of the Test.class directory, for example: the resource file myfile2.xml in the com.xyfile directory. Then, the code is as follows:

Test.class.getResourceAsStream("file/myfile2.xml");

Third: The resource file is not in the Test.class directory, nor in its subdirectory, for example: the resource file myfile3.xml in the com.x.file directory. Then, the code is as follows:

Test.class.getResourceAsStream("/com/x/file/myfile3.xml");

2. Summary

To sum up, there are actually two ways of writing.

First: path starts with '/'

Among them, "/" represents the root directory of the project.

Test.class.getResourceAsStream("/com/x/file/myfile3.xml");

Second: path does not start with '/'

Represents the directory of the current class

Test.class.getResourceAsStream("myfile.xml");

Test.class.getResourceAsStream("file/myfile2.xml"); 

Guess you like

Origin blog.csdn.net/icanlove/article/details/44097839