博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Load resources from classpath in Java--reference
阅读量:7066 次
发布时间:2019-06-28

本文共 2051 字,大约阅读时间需要 6 分钟。

In general classpath is the path where JVM can find .class files and resources of your application and in this tutorial we will see how to load resources such as .properties files that are on classpath.

Class' getResourceAsStream()

One way to load a resource is with getResourceAsStream() method of Class class.As an example consider the case where a .properties file is at a folder named resources.We could use getResourceAsStream method as shown in the below snippet.

 

import java.io.IOException;import java.io.InputStream;import java.util.Properties;public class ResourceLoader {	public static void main(String args[]) throws IOException{			InputStream resourcesStream = ResourceLoader.class.getResourceAsStream("/resources/resources.properties");		Properties properties = new Properties();		properties.load(resourcesStream);		System.out.println(properties.get("property.name"));	}	}

Using ClassLoader's getResourceAsStream()

Another way to load a resource is by using Classloader's getResourceAsStream() method.As an example consider the below snippet:

 

import java.io.IOException;import java.io.InputStream;import java.util.Properties;public class ResourceLoader {	public static void main(String args[]) throws IOException{			InputStream resourcesStream = ResourceLoader.class.getClassLoader().getResourceAsStream("resources/resources.properties");		Properties properties = new Properties();		properties.load(resourcesStream);		System.out.println(properties.get("property.name"));	}	}

Class'  vs ClassLoader's getResourceAsStream()

Difference between Class' and ClassLoader's getReourceAsStream() is in the way the path-to-resrouce is defined.In the case of  Class class getResourcesAsStream() accept's either the relative or the absoulute path of the resource.On the other hand ClassLoader's getResourceAsStream() method accept's only the absolute path to the resource and because of this,if  we used "/resources/resources.properties" wouldn't be found and getResourceAsStream() would return null

http://www.java-only.com/LoadTutorial.javaonly?id=118

 

转载地址:http://yrtll.baihongyu.com/

你可能感兴趣的文章
Oracle 正确删除archivelog文件
查看>>
微信JS 关闭网页
查看>>
[AAuto]给百宝箱增加娱乐功能
查看>>
Tigase XMPP Server源码部署
查看>>
Intellij IDEA创建Maven Web项目
查看>>
java 7 入门书籍
查看>>
Android Pdf文档的生成、显示与打印
查看>>
SpringMVC三种异常处理方式
查看>>
w命令
查看>>
golang使用oracle碰到go/lib/time/zoneinfo.zip: no such file or directory
查看>>
quartz定时任务时间设置描
查看>>
ES6常用语法
查看>>
https://www.jianshu.com/p/dbffae16ba0b
查看>>
微信,QQ这类IM app怎么做——谈谈Websocket
查看>>
在Ubuntu 11.04中安装Openresty
查看>>
JAVA常见的面试题
查看>>
《Python高效开发实战》实战演练——建立应用2
查看>>
java: -source 1.6 中不支持 switch 中存在字符串.....
查看>>
Confluence 6 空间
查看>>
lua-resty-http上传数据
查看>>