项目经常会读取一些配置文件, 因此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

工程包结构

浅谈getResource方法

 

相关文章:

  • 2021-09-18
  • 2021-05-19
  • 2022-03-06
  • 2022-02-09
  • 2021-10-29
猜你喜欢
  • 2021-12-07
  • 2021-09-27
  • 2021-06-02
  • 2021-06-23
相关资源
相似解决方案