浅谈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

工程包结构

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM