简体   繁体   English

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

[英]Spring Boot: can't load file from resources

I have few files with SQL queries in my Spring Boot project. 我的Spring Boot项目中有几个带有SQL查询的文件。 These queries are located by path 这些查询按路径定位

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

When I run my application I execute loading of these queries to static variables. 当我运行我的应用程序时,我将这些查询加载到静态变量中。

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();
    }
}

It works fine when I run it using IDE but it doesn't work when I run name.jar file, I get the following error: 当我使用IDE运行它时,它工作正常,但是当我运行name.jar文件时,它不工作,出现以下错误:

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

How can I fix this path? 如何解决此问题?

src/main/resources like src/main/java becomes the root of your classpath and as such won't work. src/main/java这样的src/main/resources成为您的类路径的根,因此将无法工作。 It won't work with only sql as well as it isn't a file when packaged as a jar . 打包成jar时,它不仅适用于sql ,也不适用于文件。 Instead use the Spring Resource abstraction to load the file and the StreamUtils to load it into a String . 相反,使用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();
    }
}

Something like that should do the trick. 这样的事情应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM