zoukankan      html  css  js  c++  java
  • Load resources from classpath in Java--reference

    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

  • 相关阅读:
    “智慧城市”长啥样?人工智能打造最具幸福感生态城
    崔宝秋:技术是小米立业之本
    搜狗发布新研究:语音+唇语让语音识别更准确
    当深圳变成一座数字花园
    中科大开发出“超长焦相机”,最远能监控 45 公里内的目标
    斯坦福黑科技打造新型交互机器人:看视频一学就会!
    机器人已经开始影响你的生活 你准备好了吗?
    说取代医生为时尚早,但AI已为颠覆医疗业埋下伏笔
    Exception testing
    Matchers and assertthat
  • 原文地址:https://www.cnblogs.com/davidwang456/p/3775549.html
Copyright © 2011-2022 走看看