问题
- 问题出现的代码
String ss = Objects.requireNonNull(app.getClass().getClassLoader().getResource(config.properties")).getPath();
System.out.println("当前获取的地址为: " + ss);
try {
FileSystemResource fileInputStream = new FileSystemResource(new File(ss));
//
Properties properties = new Properties();
properties.load(fileInputStream.getInputStream());
String property = properties.getProperty("test");
System.out.println("获取其值: " + property);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
问题原因: 在文件存在的情况下,可以读取到文件路径,但是fileInputStream.getInputStream()
会出现找不到文件的情况,在翻阅底层并没什么收获,底层是native
的方法,看不到原因(猜测是 路径中带不能识别的字符)
更改为如下代码
InputStream inputStream = Objects.requireNonNull(app.getClass().getClassLoader().getResourceAsStream("config.properties"));
try {
//
Properties properties = new Properties();
properties.load(inputStream);
String property = properties.getProperty("test");
System.out.println("获取其值: " + property);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
getResourceAsStream
方法会获取到路径url
后从URLStreamHandler
建立的链接中获取到流。这样就不会存在上面fileInputStream
找不到路径的问题。