使用SpringBoot读取资源文件夹中的可用文件

时间:2017-10-04 11:11:57

标签: java spring spring-boot spring-framework-beans

我将在Springboot应用程序中读取resources文件夹中的可用文件。我已经使用ResourceLoader来做到这一点。但是当我尝试执行我的应用程序时,我得到了一个FileNotFoundException。

$all_posts = new WP_Query( array(
    "post_type" => "post",
    "posts_per_page" => 10000,
    "post_status" => "any"
) );
while($all_posts->have_posts()) {
    $all_posts->the_post();
    if(str_word_count($post->post_content, 0) < 300) {
        print $post->post_title . "<br />\n";
    }
}

以下是我的代码

Error creating bean with name 'demoController': Invocation of init method failed; nested exception is java.io.FileNotFoundException: class path resource [schema.graphql] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/home/dilan/Projects/demo/target/demo.jar!/BOOT-INF/classes!/schema.graphql
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:137) ~[spring-beans-4.3.9.RELEASE.jar!/:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:409) ~[spring-beans-4.3.9.RELEASE.jar!/:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1620) ~[spring-beans-4.3.9.RELEASE.jar!/:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.9.RELEASE.jar!/:4.3.9.RELEASE]

任何人都可以帮我解决这个问题

enter image description here

2 个答案:

答案 0 :(得分:4)

您可以使用ClassPathResource

像这样的Smth:

InputStream inputStream = new ClassPathResource("schema.graphql").getInputStream();

File file = new ClassPathResource("schema.graphql").getFile();

答案 1 :(得分:0)

尝试使用以下代码通过spring boot

访问ressources文件夹中的文件
 File file = new ClassPathResource("schema.graphql").getFile();