首页 > 编程语言 > 详细

Load resources from classpath in Java--reference

时间:2014-06-08 22:21:17      阅读:471      评论:0      收藏:0      [点我收藏+]

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

 

Load resources from classpath in Java--reference,布布扣,bubuko.com

Load resources from classpath in Java--reference

原文:http://www.cnblogs.com/davidwang456/p/3775549.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!