绑定完请刷新页面
取消
刷新

分享好友

×
取消 复制
Load resources from classpath in Java--reference
2020-01-06 10:50:03

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

分享好友

分享这个小栈给你的朋友们,一起进步吧。

JAVA玩具小屋
创建时间:2019-08-16 16:54:49
分享程序开发方面的小经验,思考一些比较简单易懂的技术问题
展开
订阅须知

• 所有用户可根据关注领域订阅专区或所有专区

• 付费订阅:虚拟交易,一经交易不退款;若特殊情况,可3日内客服咨询

• 专区发布评论属默认订阅所评论专区(除付费小栈外)

栈主、嘉宾

查看更多
  • Yios5092
    栈主

小栈成员

查看更多
  • 栈栈
  • coyan
  • 25minutes
  • ?
戳我,来吐槽~