className.class.getResourceAsStream()与ClassLoader.getSystemResourceAsStream() 的区别

来源:互联网 发布:重庆网络问政平台回复 编辑:程序博客网 时间:2024/06/06 07:53

1.className.class.getResourceAsStream

第一: 要加载的文件和.class文件在 同一目录 下,例如:com.x.y 下有类Test.class ,同时有资源文件config.properties

那么,应该有如下代码:
//前面没有“/”代表当前类的目录

InputStream is1 = Test.class.getResourceAsStream("config.properties"); System.out.println(is1);// 不为null

第二:在Test.class目录的 子目录 下,例如: com.x.y 下有类Test.class ,同时在 com.x.y.prop 目录下有资源文件config.properties

那么,应该有如下代码:
//前面没有“/”代表当前类的目录

InputStream is2 = Test.class.getResourceAsStream("prop/config.properties"); System.out.println(is2);//不为null

第三: 不在同目录 下,也 不在子目录 下,例如: com.x.y 下有类Test.class ,同时在 com.m.n 目录下有资源文件config.properties

那么,应该有如下代码:
// 前面有“/” , 代表了工程的根目录

InputStream is3 = Test.class.getResourceAsStream("/com/m/n/config.properties");System.out.println(is3);//不为null

2.ClassLoader.getSystemResourceAsStream

ClassLoader.getSystemResourceAsStream 和className.class.getResourceAsStream 的第三种取得的路径一样, 但少了“/”

InputStream is4 = ClassLoader.getSystemResourceAsStream("properties/PayManagment_Config.properties"); System.out.println(is4);//不为null
0 0
原创粉丝点击