Java learning series: the use of getResourceAsStream or getResource

Scenes

In the program, you need to obtain configuration files or resource files, you can use getResourceAsStream or getResource to obtain resources. This blog post is mainly about the usage of this usage.

surroundings

software version
Java 8

text

show the code!!!

public class TestGetResource {
    
    
    public static void main(String[] args) {
    
    
        TestGetResource testGetResource = new TestGetResource();

        testGetResource.testResource();
        testGetResource.testTest1_2();
        testGetResource.testTest1();
    }

    private void testResource() {
    
    
        System.out.println("从classpath路径下找该文件");
        InputStream resource = this.getClass().getClassLoader().getResourceAsStream("test.properties");
        String resourceLine = IoUtil.read(resource, Charset.forName("UTF-8"));
        System.out.println("读取this.getClass().getClassLoader().getResourceAsStream(\"test.properties\")的值为:"+resourceLine);
    }

    private void testTest1() {
    
    
        System.out.println("从当前路径下找该文件");
        InputStream resource = this.getClass().getResourceAsStream("test.properties");
        String resourceLine = IoUtil.read(resource, Charset.forName("UTF-8"));
        System.out.println("读取this.getClass().getResourceAsStream(\"test.properties\")的值为:"+resourceLine);
    }

    private void testTest1_2() {
    
    
        System.out.println("加入/,则从classpath路径下找该文件");
        InputStream resource = this.getClass().getResourceAsStream("/test.properties");
        String resourceLine = IoUtil.read(resource, Charset.forName("UTF-8"));
        System.out.println("读取this.getClass().getResourceAsStream(\"/test.properties\")的值为:"+resourceLine);
    }
}

The results are as follows:

从classpath路径下找该文件
读取this.getClass().getClassLoader().getResourceAsStream("test.properties")的值为:index=resource

加入/,则从classpath路径下找该文件
读取this.getClass().getResourceAsStream("/test.properties")的值为:index=resource

从当前路径下找该文件
读取this.getClass().getResourceAsStream("test.properties")的值为:index=test1

Expand

this.getClass().getResourceAsStream 返回 null

  1. Check whether the file name and file path are normal;
  2. Check whether there is a path generated to the corresponding classes. If the file is placed in the source directory, the compilation and packaging may not copy the non-java files. Need special settings! ! !

to sum up

Think more! ! !

Ask for praise

If my article is helpful to everyone, you can click like or favorite at the bottom of the article;
if there is a good discussion, you can leave a message;
if you want to continue to view my future articles, you can click Follow
You can scan the following QR code to follow me 'S public account: Fengye Zhixuege, check out my latest share!
Insert picture description here
Bye bye

Guess you like

Origin blog.csdn.net/u013084266/article/details/112270671