首页 > 其他 > 详细

ClassLoader.getResourceAsStream() 与 Class.getResourceAsStream()的区别

时间:2017-02-07 14:13:27      阅读:366      评论:0      收藏:0      [点我收藏+]
package com.xinwei.util;


import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesLoader {
    public static void main(String[] args) {
//        test1();
        test2();
    }
//在使用Class.getResourceAsStream 时, 资源路径有两种方式, 一种以 / 开头,则这样的路径是指定绝对路径,
// 如果不以 / 开头, 则路径是相对与这个class所在的包的。
    private static void test2() {
        InputStream in = PropertiesLoader.class.getResourceAsStream("/register.properties");  
        Properties prop = new Properties();  
        try {
            prop.load(in);
            String roleId = prop.getProperty("request.roleIds"); 
            System.out.println(roleId);
        } catch (IOException e) {
            e.printStackTrace();
        }  
        
    }
    //在使用ClassLoader.getResourceAsStream时, 路径直接使用相对于classpath的绝对路径
    private static void test1() {
        InputStream in =PropertiesLoader.class.getClassLoader().getResourceAsStream("register.properties");  
        Properties prop = new Properties();  
        try {
            prop.load(in);
            String roleId = prop.getProperty("request.roleIds"); 
            System.out.println(roleId);
        } catch (IOException e) {
            e.printStackTrace();
        }  
        
    }
}
//举例,下面的三个语句,实际结果是一样的:
//com.explorers.Test.class.getResourceAsStream("abc.jpg")
//= com.explorers.Test.class.getResourceAsStream("/com/explorers/abc.jpg")
//= ClassLoader.getResourceAsStream("com/explorers/abc.jpg") 

 

ClassLoader.getResourceAsStream() 与 Class.getResourceAsStream()的区别

原文:http://www.cnblogs.com/alamps/p/6373654.html

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