getResourceAsStream uses in Java

Source: Internet
Author: User

In fact, I do not understand this thing, in the project encountered, I faint feeling this is in the reading of a file information, and then consulted the relevant blog, probably summed up some of this thing is what to do.

First, we need to know what getResourceAsStream are in Java and what the parameters mean.

The primary function is to read the specified file and return an input stream object

1. This is the way I see it in the project

Server.class.getResourceAsStream ("Jdbc.properties")//reads the specified file, returns an input stream InputStream object

Parameter description: There are two types of parameters: one is "/", which means to start with the classpath of the project, if there is no previous "/", then the path relative to the class continues down

For example, suppose the Server path is "/com/utils/server.java"

Then the parameter: "jdbc.properties" means "/com/utils/jdbc.properties"

"/jdbc.properties" is the same level as COM.

"jdbc/jdbc.properties" is "/com/utils/jdbc/jdbc.properties".

2. Another way

Server.getClassLoader.getResourceAsStream ("Jdbc.properties")

Parameter description: The parameters here are defaulted from the classpath of the project, so the parameters cannot begin with "/", which will conflict

3. ServletContext. getResourceAsStream (String path): The default is to fetch resources from the WebApp root directory, and whether or not Tomcat starts with '/' does not matter, 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.


In summary: 1. The function is to read the specified file and return an object of the input stream, or a null (when the file does not exist)

2. There are only two ways of parameter, one is "/", which means that the classpath path is the starting point, and the other is the beginning of the path without "/", which indicates that the current class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.