码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-02-07 14:13:31      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:try   out   system   log   ssl   loader   register   package   stat   

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()的区别

标签:try   out   system   log   ssl   loader   register   package   stat   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!