SpringBoot--程式碼方式讀取properties出現異常解決
阿新 • • 發佈:2019-01-05
問題
- 問題出現的程式碼
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
找不到路徑的問題。