简单示例
此处的类 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")