假設靜態資源文件 information.txt 放在 src/main/resources 目錄下
public String getInfo() {
String msg = "";
InputStreamReader intput = null;
try {
Resource resource = new ClassPathResource("information.txt");
File file = resource.getFile();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
msg = reader.readLine();
} catch (Exception e) {
log.error(e.getMessage());
}
return msg;
}
注意:
如果將該項目打包運行在Linux系統下,該方法無法讀取文件,報錯信息爲cannot be resolved to absolute file path because it does not reside in the file system。這是因爲在Linux系統下,spring無法訪問jar中的路徑。
解決方法:
使用ClassPathResource類的getInputStream方法獲取InputStream
Linux讀取resources目錄下文件:
public String getInfo() {
String msg = "";
InputStreamReader intput = null;
try {
Resource resource = new ClassPathResource("information.txt");
// 修改部分
intput = new InputStreamReader(resource.getInputStream());
BufferedReader reader = new BufferedReader(intput);
msg= reader.readLine();
} catch (Exception e) {
log.error(e.getMessage());
}
return msg;
}