亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Spring Boot 上讀取部署時的靜態文件

如何在 Spring Boot 上讀取部署時的靜態文件

肥皂起泡泡 2021-10-06 12:42:44
我希望能夠在 heroku 上在線部署我的 Spring Boot 應用程序。我的應用程序從位于我的資源文件夾中的靜態 .json 文件加載數據。到目前為止,我已經嘗試過這段代碼,但它不起作用。出于某種原因,我無法從 json 文件中讀取數據。    public List<Category> getAllCategories() throws FileNotFoundException    {       Gson gson = new Gson();       ClassLoader classLoader = getClass().getClassLoader();       File file = new File(classLoader.getResource("static/data/data.json").getFile());       JsonReader reader = new JsonReader(new FileReader(file.getPath()));       List<Category> allCategories = gson.fromJson(reader, new TypeToken<List<Category>>(){}.getType());       return allCategories;    }
查看完整描述

2 回答

?
倚天杖

TA貢獻1828條經驗 獲得超3個贊

由于data.json移動它被部署在Heroku里面JAR,請嘗試使用getResourceAsStream(path)替代getResource()。偽代碼可能是,


Gson gson = new Gson();

ClassLoader classLoader = getClass().getClassLoader();

InputStream in = classLoader.getResourceAsStream("static/data/data.json");

JsonReader reader = new JsonReader(new InputStreamReader(in));

List<Category> allCategories = gson.fromJson(reader, new TypeToken<List<Category>>(){}.getType());



查看完整回答
反對 回復 2021-10-06
?
慕少森

TA貢獻2019條經驗 獲得超9個贊

您能否將數據文件夾直接移動到資源下,因為靜態資源路徑在這里可能會發生沖突,下面的使用應該可以工作。

File file = new File(classLoader.getResource("data/data.json").getFile());


查看完整回答
反對 回復 2021-10-06
  • 2 回答
  • 0 關注
  • 185 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號