Spring Boot:无法从资源加载文件

时间:2017-10-11 13:09:51

标签: java spring-boot

我的Spring Boot项目中有很少的SQL查询文件。这些查询按路径

定位
spring-boot-sql-in-files/src/main/resources/sql/query.sql

当我运行我的应用程序时,我执行将这些查询加载到静态变量。

private static final String PATH_PREFIX = "src/main/resources/sql/";

public static String loadQueryFromFile(@NonNull String fileName) {
    try {
        return FileUtils.readFileToString(new File(PATH_PREFIX + fileName), Charset.defaultCharset());
    } catch (Exception e) {
        log.error("Error occurred during loading sql file to string, file=" + fileName, e);
        throw new QueryNotLoadedException();
    }
}

当我使用IDE运行它时工作正常但是当我运行name.jar文件时它不起作用,我收到以下错误:

java.io.FileNotFoundException: File 'src/main/resources/sql/query.sql' does not exist

如何修复此路径?

1 个答案:

答案 0 :(得分:7)

src/main/resources这样的{p> src/main/java成为了类路径的根,因此无效。它不仅适用于sql,也不适用于打包为jar时的文件。而是使用Spring Resource抽象加载文件,使用StreamUtils将其加载到String

public static String loadQueryFromFile(@NonNull String fileName) {
    try {
        Resource resource = new ClassPathResource("sql/" + fileName);
        return StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset());
    } catch (Exception e) {
        log.error("Error occurred during loading sql file to string, file=" + fileName, e);
        throw new QueryNotLoadedException();
    }
}

这样的事情应该可以解决问题。