类加载器加载配置文件的几种写法

    public static void main(String[] args) throws Exception{
        // TODO Auto-generated method stub
        /*getRealPath();//金山词霸/内部
        一定要记住用完整的路径,但完整的路径不是硬编码,而是运算出来的。*/
        //InputStream ips = new FileInputStream("config.properties");
       
        //InputStream ips = ReflectTest2.class.getClassLoader().getResourceAsStream("cn/itcast/day1/resources/config.properties"); 通过显式调用类加载器方式 注意路径中根位置没有/
        //InputStream ips = ReflectTest2.class.getResourceAsStream("resources/config.properties"); 通过封装的方法加载,注意里面的路径是相对于ReflectTest2的相对路径
        // 使用类路径下找到文件的方式 更容易让人接受
        InputStream ips = ReflectTest2.class.getResourceAsStream("/cn/itcast/day1/resources/config.properties");// 通过封装的方法加载,这里的路径为绝对路径,此时需要加上根路径的/
        //InputStream ips = ReflectTest2.class.getResourceAsStream("/resources/config.properties"); 加载根路径下的配置文件 此时也只能使用绝对路径来加载
        Properties props = new Properties();
        props.load(ips);
        ips.close();
        String className = props.getProperty("className");
        System.out.println("className: " + className);
        /*
        Collection collections = (Collection)Class.forName(className).newInstance();
       
        //Collection collections = new HashSet();
        ReflectPoint pt1 = new ReflectPoint(3,3);
        ReflectPoint pt2 = new ReflectPoint(5,5);
        ReflectPoint pt3 = new ReflectPoint(3,3);   

        collections.add(pt1);
        collections.add(pt2);
        collections.add(pt3);
        collections.add(pt1);   
       
        //pt1.y = 7;       
        //collections.remove(pt1);
       
        System.out.println(collections.size());
        */
    }

 

主要就是要知道类加载器的方法getResourceAsStream写法,更倾向于使用方式3,因为方式3简洁并且可以加载根路径下和包路径下

1 ReflectTest2.class.getClassLoader().getResourceAsStream("cn/itcast/day1/resources/config.properties");

2 InputStream ips = ReflectTest2.class.getResourceAsStream("/cn/itcast/day1/resources/config.properties");// 通过封装的方法加载,这里的路径为绝对路径,此时需要加上根路径的/


3 InputStream ips = ReflectTest2.class.getResourceAsStream("/resources/config.properties"); 加载根路径下的配置文件 此时也只能使用绝对路径来加载

 

 

你可能感兴趣的:(类加载器,加载配置文件)