一開始我的代碼是這樣子的,讀取本地子路徑下的json檔案
代碼運作的時候,在window是可以正常的
@Override
public String getBannerStr() {
String str = "";
try {
Resource resource = new ClassPathResource("json/abc.json");
File file = resource.getFile();
str = FileUtils.readFileToString(file, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException("Json資訊查詢出錯");
}
return str;
}
但是實際上,工程是在Linux上面部署為jar包的
上面通路方式就出錯了,這邊一開始以為是擷取資源檔案的方式出問題了
後來試了幾次,發現問題不是這樣.
最後百度發現,在Linux中無法直接通路未經解壓的檔案,是以就會找不到檔案。
是以隻能使用流的方式對靜态資源進行讀取
下面是最後修改的代碼
@Override
public String getBannerStr() {
String str = "";
try {
InputStream stream = getClass().getClassLoader().getResourceAsStream("json/abc.json");
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String s = "";
try {
while ((s = br.readLine()) != null) {
str = str + s;
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException("Json資訊查詢出錯");
}
return str;
}