Java专题 类加载器获取文件流,转properties并获取的内容,以及读取线程锁

简单示例

此处的类 MyLambda 就是我的当前类

synchronized (MyLambda.class){
// 通过当前类的类加载器获取文件流
      InputStream resourceAsStream = System.class.getClassLoader().getResourceAsStream("/home/a.properties");

	 // 转为properties并加载
      Properties properties = new Properties();
      properties.load(resourceAsStream);

	// 读取properties中的值
      String enc_key = (String) properties.get("enc_key");

     }

synchronized 是为了防止多线程访问的时候多次读取,但读取内容完全,导致之后多次取值时可能出现取值不完全的问题

synchronized 中可以放当前类,也可以在当前类定义常量 ,例如字符串 ,均是为了保证当前访问的只有一个,不能用对象,this ,因为每一次执行,对象都不能保证是同一个对象。

也可以如下拼接

this.getClass().getClassLoader().getResource("/").getPath() + "download" + File.separator + fileName

IO 指定编码 UTF-8

前面放文件路径,后面指定编码
MyClass 为当前文件的类名

InputStreamReader inputStreamReader = new InputStreamReader(MyClass.class.getClassLoader()
                .getResourceAsStream("/myproper.properties"), "UTF-8")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值