GetResourceAsStream usage analysis in Java

  • 2020-04-01 03:55:27
  • OfStack

This article illustrates the use of getResourceAsStream in Java. Share with you for your reference. The details are as follows:

(a) getResourceAsStream in Java has the following situations:

1. Class. GetResourceAsStream (String path) :

When #path does not start with '/', the default is to fetch the resource from the package that this class is in.
# starts with '/' and is fetched from the ClassPath root by constructing an absolute path through the path, which is ultimately retrieved by the ClassLoader.

2. Class. GetClassLoader. GetResourceAsStream (String path) :

The default is taken from the ClassPath root, the path does not start with '/', and the ClassLoader ultimately takes the resource.

Servletcontext.getresourceasstream (String path) :

It doesn't matter if the path under Tomcat or Resin#[Web container] starts with '/', depending on the container implementation.

4. The application built-in object under Jsp is an implementation of the ServletContext above.

(ii) getResourceAsStream can be used in the following ways:

First: the file to be loaded is in the same directory as the.class file, for example: com.x.y has the class me.class and the resource file myfile.xml

Then, you should have the following code:

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

Second: under the subdirectory of the me.class directory, for example: com.x.y, there is the class me.class, and at the same time, there is the resource file myfile.xml under the com.x.y.ile directory

Then, you should have the following code:

me.class.getResourceAsStream("file/myfile.xml");

Third: not in the directory of me. Class, not in the subdirectory, for example: com.x.y under the class me. Class, at the same time in the directory of com.x.ile resource file myfile.xml

Then, you should have the following code:

me.class.getResourceAsStream("/com/x/file/myfile.xml");

(3) as follows, there may be only two ways of writing

First: preceded by the word "    /"

"/" represents the root directory of the project, for example, the project name is myproject, and "/" represents myproject
The same code at the page code block index 2

Second: no "    /"

Represents the directory of the current class

me.class.getResourceAsStream("myfile.xml");
me.class.getResourceAsStream("file/myfile.xml");

I hope this article has been helpful to your Java programming.


Related articles: