//20201226
写在前面:学习java反射的时候老师讲了一个获取绝对路径的通用方法,在此记录一下
获取规则:
- 文件必须在项目类路径下:即src文件夹内,外部文件无法获取
- 获取方式如下:
String path1 = Thread.currentThread().getContextClassLoader().getResource("io/uerinfo.properties").getPath();
System.out.println(path1);
String path2 = Thread.currentThread().getContextClassLoader().getResource("uerinfo.properties").getPath();
System.out.println(path2);
- 文件位置截图如下:
- 输出截图如下:
直接从文件名获取流
- //20201226 11:46更新
- 代码如下:
InputStream io = Thread.currentThread().getContextClassLoader().getResourceAsStream("io/uerinfo.properties");
Properties test = new Properties();
test.load(io);
io.close();
System.out.println(test.get("username"));
System.out.println(test.get("password"));
System.out.println(test.get("driver"));
使用资源绑定器
- //20201226更新
- 限制:
- 只能绑定properties文件
- 配置文件必须放在类目录下,外部文件无法绑定
- 优点:便捷
- 代码如下:
ResourceBundle rb = ResourceBundle.getBundle("uerinfo");
String username = rb.getString("username");
System.out.println(username);