The examples in this article describe the getResourceAsStream usage in Java. Share to everyone for your reference. Specifically as follows:
(a) The getResourceAsStream in Java has the following situations:
1. Class.getresourceasstream (String path):
#path does not start with '/' By default is to fetch resources from the package where this class resides;
#以 '/' begins with the classpath root, the principle of which is to construct an absolute path through path, and ultimately to ClassLoader to obtain resources.
2. Class.getClassLoader.getResourceAsStream (String path):
#默认则是从ClassPath根下获取, path cannot start with '/', and ultimately, the resource is acquired by ClassLoader.
3. ServletContext. getResourceAsStream (String path):
#默认从WebAPP根目录下取资源, whether the path under Tomcat or Resin#[web container] starts with '/' does not matter, of course this is related to the specific container implementation.
4. The application built-in object under the JSP is an implementation of the ServletContext above.
(b) The following getresourceasstream are roughly used:
First: The files and. class files to be loaded are in the same directory, for example: Com.x.y have class Me.class, and resource files Myfile.xml
Then, you should have the following code:
Copy Code code as follows:
Me.class.getResourceAsStream ("Myfile.xml");
Second: In the subdirectory of the Me.class directory, for example, there is a class of me.class under Com.x.y, and a resource file is available under the Com.x.y.file directory Myfile.xml
Then, you should have the following code:
Copy Code code as follows:
Me.class.getResourceAsStream ("File/myfile.xml");
Third: Not in the Me.class directory, nor in subdirectories, such as: Com.x.y under the class Me.class, while the Com.x.file directory has a resource file Myfile.xml
Then, you should have the following code:
Copy Code code as follows:
Me.class.getResourceAsStream ("/com/x/file/myfile.xml");
(c) summed up as follows, probably just two ways of writing
First: The front has "/"
"/" represents the root of the project, such as the project name MyProject, "/" represents the MyProject
Copy Code code as follows:
Me.class.getResourceAsStream ("/com/x/file/myfile.xml");
Second: no Front "/"
Represents the directory of the current class
Copy Code code as follows:
Me.class.getResourceAsStream ("Myfile.xml");
Me.class.getResourceAsStream ("File/myfile.xml");
I hope this article will help you with your Java programming.