资源文件的操作结合反射

1. 资源文件所存放的位置
   资源文件放在cn.lyr包下。
2. 获取系统资源文件的方式有2中

 

        a:通过  InputStream io=ReflectTest2.class.getResourceAsStream("/cn/lyr/config.properties");
        b:通过  InputStream io=ReflectTest2.class.getClassLoader().getResourceAsStream("cn/lyr/config.properties");
采用第一种方式获取资源文件时,文件必须以"/" 开头,而采用方法b的话,文件不以"/"开头

3.加载资源信息

  InputStream io=ReflectTest2.class.getClassLoader().getResourceAsStream("cn/lyr/config.properties");
  Properties pro=new Properties();
  pro.load(io);
  io.close();
  String className=pro.getProperty("className");
  System.out.println(Class.forName(className).getName());
  List<String> list=(List)Class.forName(className).newInstance();
  list.add("aaa");
  list.add("bbb");
  list.add("ccc");
  for (String string : list) {
       System.out.println(string);
  }

4.向资源文件中添加键值信息,如果key值相同就会将原有的信息覆盖

URL url=ClassLoader.getSystemResource("cn/lyr/config.properties");
  System.out.println(url);
  File file=new File(url.toURI());
  InputStream io=new FileInputStream(file);
  Properties p=new Properties();
  p.load(io);
  p.setProperty("className", "java.util.LinkedList");
  OutputStream out=new FileOutputStream(file);
  //Properties 表中的属性列表(键和元素对)写入输出流。
  p.store(out, null);
  out.flush();
  io.close();

5,删除键值信息

File file = new File(ClassLoader.getSystemResource("cn/lyr/config.properties").toURI());   

InputStream is = new FileInputStream(file);   

  

properties.load(is);   

properties.remove("key");   

  

OutputStream fos = new FileOutputStream(file);   

properties.store(fos, null);   

  

is.close();   

fos.flush();   

fos.close();  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值