classloader读取配置文件_类加载器加载配置文件的几种写法

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"); 加载根路径下的配置文件 此时也只能使用绝对路径来加载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值