在jar build b spring boot中找不到文件

pvcm50d1  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(377)

这些日志和控制器类是不言自明的:
日志:

java.io.FileNotFoundException: class path resource [/static/index.html] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/home/mehrdad/ocr/main/ocr-web/target/ocr-web-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static/index.html
    at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:217)
    at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:180)
    at com.pouya.ocr.web.web.RouteController.defaultPath(RouteController.java:23)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

班级:

@Controller
public class RouteController {
    @RequestMapping(value = "/app/**", method = RequestMethod.GET)
    public ResponseEntity<String> defaultPath() {
        System.out.println("Unmapped request handling!");
        try {
            File index = ResourceUtils.getFile("classpath:/static/index.html");
            FileInputStream inputStream = new FileInputStream(index);
            String body = StreamUtils.copyToString(inputStream, Charset.defaultCharset());
            return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(body);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error in redirecting to index");
        }
    }

}
第二个!似乎导致了问题:

../ocr-web-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static/index.html

如何解决这个问题?
我试着用 classpath:static/index.html 而不是 classpath:/static/index.html ,没有任何变化。

nbysray5

nbysray51#

我解决了这个问题。
不要使用 ResourceUtils (有时spring并不能使java更简单!)使用旧的java方式从类路径加载资源:

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("/static/index.html");

相关问题