Home  >  Article  >  Java  >  How Java uses the getClass().getResourceAsStream() method to obtain resource instance analysis

How Java uses the getClass().getResourceAsStream() method to obtain resource instance analysis

黄舟
黄舟Original
2017-07-24 15:42:272610browse

This article mainly introduces the relevant information about Java using the getClass().getResourceAsStream() method to obtain resources. Here we mainly explain which method can obtain file resources. Friends in need can refer to it

Java uses the getClass().getResourceAsStream() method to obtain resources

I wanted to obtain a resource file for some processing before, but could not get the file using getClass().getResourceAsStream(). Specific usage.


1 InputStream is = this.getClass().getResourceAsStream(fileName);  //拿不到资源
2 InputStream is = this.getClass().getResourceAsStream("/" + fileName); // 拿到资源
3 InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileName); //拿到资源

The location of the specific files and code is that the code is in the src/main/java directory and the resource files are in the src/main/resources/ directory.

will be searched from the directory of the current class. If this file is not in the same directory as the class, it will not be found.

will be found from the entire compiled classes directory. Maven will also package the resource files into the classes folder, so it can be found.

ClassLoader is found from the entire classes folder, so there is no need to add / in front.

The above is the detailed content of How Java uses the getClass().getResourceAsStream() method to obtain resource instance analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn