【问题标题】:Reading file available in resources folder with SpringBoot使用 Spring Boot 读取资源文件夹中可用的文件
【发布时间】:2017-10-04 11:11:56
【问题描述】:

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

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]

下面是我的代码

 @Autowired
private ResourceLoader resourceLoader;

final Resource fileResource = resourceLoader.getResource("classpath:schema.graphql");
File schemaFile = fileResource.getFile();
TypeDefinitionRegistry definitionRegistry = new SchemaParser().parse(schemaFile);
RuntimeWiring wiring = buildRuntimeWiring();

谁能帮我解决这个问题

【问题讨论】:

  • 你是对的 .. 它重复了另一个问题:stackoverflow.com/questions/41754712/… 在发布无用的问题之前,请尝试谷歌一次..
  • 您无法从jar 获取文件.. 尝试将文件作为流获取..

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


【解决方案1】:

你可以使用ClassPathResource

像这样的:

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

或者

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

【讨论】:

    【解决方案2】:

    尝试使用下面的代码通过 spring boot 访问 ressources 文件夹中的文件

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

    【讨论】:

      【解决方案3】:

      添加来自here的答案, 访问ClassPathResource并将内容复制到String

      try {
         ClassPathResource classPathResource = new ClassPathResource("schema.graphql");
         byte[] data = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
         String content = new String(data, StandardCharsets.UTF_8);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
      

      【讨论】:

        猜你喜欢
        • 2017-11-08
        • 2019-04-15
        • 2018-05-28
        • 2019-10-16
        • 2017-02-25
        • 2017-03-13
        • 1970-01-01
        • 1970-01-01
        • 2020-11-14
        相关资源
        最近更新 更多