线程安全有好几种方法,这里就写一种目前比较常用的properties资源文件获取流的方式
通过当前线程的类加载器获取流
public class propertiesTest {
@org.junit.Test
public void testName() throws Exception {
// 创建Properties对象
Properties properties = new Properties();
// 获取当前线程类的加载器
ClassLoader con = Thread.currentThread().getContextClassLoader();
// 线程安全的一种关流方式
try (
// 获取当前线程类的加载器获取流的对象 这里相对路径或者使用决定路径
InputStream resourceAsStream = con.getResourceAsStream("mysql.properties");
// 要明白properties处理的是非文本数据 当前类处理的是文本数据,所以我们需要
//进行转换流处理
InputStreamReader iSReader = new InputStreamReader(resourceAsStream);
) {
// properties对象properties调用方法
properties.load(iSReader);
// properties对象properties调用方法:getProperty获取值
String username = properties.getProperty("user");
String password = properties.getProperty("pass");
System.out.println("用户名: " + username + " 用户名密码: " + password);
} catch (Exception e) {
// TODO: handle exception
}
}
}
博客介绍了线程安全的一种常用方法,即通过当前线程的类加载器获取properties资源文件的流。
1752

被折叠的 条评论
为什么被折叠?



