浅谈getResource方法

项目经常会读取一些配置文件, 因此getResource方法便能够起到重要作用

使用时主要是两种方法, 一个是字节码文件Class类, 另一个是ClassLoader类加载器

使用Class类时有两种使用方式:

1. 使用"/"  获取到的是classpath路径

2. 不使用"/" 这就是相对路径

ClassLoader类

没有"/"的写法, 获取到的就是classpath路径

测试代码

public class GetResourceTest {

    public static void main(String[] args) {
        System.out.println(GetResourceTest.class.getResource("/test.properties").getPath());
        System.out.println(GetResourceTest.class.getResource("test1.properties").getPath());
        System.out.println(GetResourceTest.class.getClassLoader().getResource("test.properties").getPath());
        System.out.println(GetResourceTest.class.getClassLoader().getResource("/"));
    }

}

结果:

/E:/IdeaJava/studyTest/out/production/studyTest/test.properties
/E:/IdeaJava/studyTest/out/production/studyTest/com/waston/Test/test1.properties
/E:/IdeaJava/studyTest/out/production/studyTest/test.properties
null

工程包结构

原文地址:https://www.cnblogs.com/wt20/p/8320346.html