Java 类加载器—加载properties配置文件加载

Jan 18, 2017 阅读(181)

项目结构:

图片.png


测试代码:

package cn.xuexiyuan.resources;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

public class LoadResourcesTest {
    
    private static void print(Properties properties){
        Set<Entry<Object, Object>> entrys = properties.entrySet();
        for (Object object : entrys) {
            System.out.println(object);
        }
    }
    
    public static void test() throws Exception {
        System.out.println("运行 test() ...");
        InputStream inStream = null;
        Properties properties = new Properties();
        
        //【正常加载】 加载项目根目录下的 package-external.properties 文件
        inStream = LoadResourcesTest.class.getClassLoader().getResourceAsStream("package-external.properties");
        properties.load(inStream);    inStream.close();
        print(properties);
        
        
        //【正常加载】  加载 LoadResourcesTest 类所在路径下的  package-inner.properties文件
        inStream = LoadResourcesTest.class.getResourceAsStream("package-inner.properties");
        properties.load(inStream);    inStream.close();
        print(properties);
        
        //【正常加载】  加载根目录下 package-external.properties 文件, "/" 表示类加载器的根路径
        inStream = LoadResourcesTest.class.getResourceAsStream("/package-external.properties");
        properties.load(inStream);    inStream.close();
        print(properties);
    }
    
    public static void execptionLoad(){
        System.out.println("运行 execptionLoad() ...");
        InputStream inStream = null;
        
        //【异常加载】Object.class 同级目录找不到配置文件 package-external.properties
        inStream = Object.class.getResourceAsStream("package-external.properties");
        if(null == inStream){
            System.err.println("Object.class 加载不到 package-external.properties 配置文件");
        }
        
        //【异常加载】  LoadResourcesTest.class 同级目录找不到配置文件 package-external.properties
        inStream = LoadResourcesTest.class.getResourceAsStream("package-external.properties");
        if(null == inStream){
            System.err.println("LoadResourcesTest.class 加载不到 package-external.properties 配置文件");
        }
        
        //【异常加载】 抛 Exception in thread "main" java.io.FileNotFoundException: package-external.properties (系统找不到指定的文件。)
        try {
            inStream = new FileInputStream("package-external.properties");
        } catch (FileNotFoundException e) {
            System.err.println("加载 package-external.properties 异常,"+e.getMessage());
        }
    }

    
    
    public static void main(String[] args) throws Exception {
        test();
        execptionLoad();
    }

}