gson 如何在Sping Boot 上读取Heroku部署的静态文件

b5lpy0ml  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(120)

我如何解决这种情况?我在src/main/resources上有一个静态JSON文件,当我运行代码时,我使用此JSON创建一些数据,但当我尝试在heroku上部署时,我收到此错误,可能是因为他们找不到FUNDOS.json文件。
有人知道怎么解决这个问题吗?
编码

String FUNDOS_JSON = "src/main/resources/data/FUNDOS.json";
Path filePath = Path.of(FUNDOS_JSON).toAbsolutePath();
String jsonString = Files.readString(filePath);

JSONArray json = new JSONArray(jsonString);

错误

remote:        [ERROR] COMPILATION ERROR :
remote:        [INFO] -------------------------------------------------------------
remote:        [ERROR] /tmp/build_835ef365/src/main/java/br/anbima/mvc/service/AnbimaServiceImpl.java:[36,37] cannot find symbol
remote:          symbol:   method of(java.lang.String)
remote:          location: interface java.nio.file.Path
remote:        [ERROR] /tmp/build_835ef365/src/main/java/br/anbima/mvc/service/AnbimaServiceImpl.java:[37,42] cannot find symbol
remote:          symbol:   method readString(java.nio.file.Path)
remote:          location: class java.nio.file.Files
remote:        [INFO] 2 errors
lawou6xi

lawou6xi1#

对于src/main/resources内的资源,请使用getResourceAsStream或getResource。
假设您的代码位于一个名为www.example.com的文件中Foo.java,

InputStream fundosStream = Foo.class.getResourceAsStream("/data/FUNDOS.json");
String fundosContent = "";
try(BufferedReader br = new BufferedReader(new InputStreamReader(fundosStream)) {
     String line = br.readLine();
     while(line != null) {
         fundosContent = line + "\n";
         line = br.readLine();
     }
} catch(IOException ioe) {
     ioe.printStackTrace();
}
JSONArray jsonArray = new JSONArray(fundosContent);

相关问题