加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Load resources from classpath in Java--reference

发布时间:2020-12-14 06:18:18 所属栏目:Java 来源:网络整理
导读: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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读