美文网首页
获取包下资源

获取包下资源

作者: 吐痰高手 | 来源:发表于2017-11-08 22:15 被阅读6次

当需要获取包下的资源时就可以用这种方式

Url url = Class.getResource(String path)
//path  不以’/'开头时,默认是从此类所在的包下取资源;
//path  以’/'开头时,则是从ClassPath根下获取;
/*
 * 如果是文件的话
 * url.getPath() 就是这个文件或者文件夹的路径
 */
当然,考虑到编码的问题,
最好还是利用如下方法转化为utf-8的编码 让java能够绝对的识别正确
String path = URLDecoder.decode(url.getPath(), "UTF-8")
如果是文件或者文件夹的话,就可以生成File对象了
File file = new File(path);

直接获取输入流

this.getClass().getResourceAsStream("/db.properties");
//等同于下方的代码

ClassLoader classLoader = this.getClass().getClassLoader();
URL url = classLoader.getResource("/db.properties");
InputStream is= url.openConnection().getInputStream();

Properties读取文件

Properties p = new Properties();
p.load(getClass().getResourceAsStream("/db.properties"));

相关文章

网友评论

      本文标题:获取包下资源

      本文链接:https://www.haomeiwen.com/subject/tarumxtx.html