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

本文介绍两种在Java中加载属性文件的方法:使用Class.getResourceAsStream通过绝对路径加载和使用ClassLoader.getResourceAsStream加载。并解释了路径配置的区别。
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") 

 

转载于:https://www.cnblogs.com/alamps/p/6373654.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值