spring boot 讀取 resources 下的文件,把文件內容讀到String中

File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+"static/detect.js");

String result = IOUtils.toString(new FileInputStream(file), String.valueOf(StandardCharsets.UTF_8));

上面的方法也行,但是打包後,會有

cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/suning-service-api.jar!/BOOT-INF/classes!/static/detect.js  的錯誤

還有另外一種方式

ClassPathResource resource = new ClassPathResource("static/detect.js");
InputStream inputStream = resource.getInputStream();
String result = IOUtils.toString(inputStream, String.valueOf(StandardCharsets.UTF_8));

從流中讀取一行

//讀取一行
IOUtils.readLines(inputStream).forEach(System.out::println);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章