2017-10-04 1011 views
1

我將在我的Springboot應用程序的資源文件夾中讀取一個可用文件。我已經使用ResourceLoader來做到這一點。但是當我嘗試執行我的應用程序時,我得到一個FileNotFoundException。使用SpringBoot讀取資源文件夾中的文件

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

任何人可以幫我理清了這一點

enter image description here

+0

@Yannic克萊姆NO ......這不是你提到的問題的副本。使用ClassLoader在這裏不起作用。在這裏,我正在問我們如何使用ResourceLoader訪問文件。這兩個怎麼可能相似....?請嘗試閱讀甚至在做無用的評論之前的內容 – user5489038

+0

你是對的..它重複另一個問題:https://stackoverflow.com/questions/41754712/spring-boot-reading-text-file-using-resourceloader請嘗試甚至谷歌一次發佈無用的問題之前.. –

+0

你不能從'jar'獲取文件..嘗試獲取文件作爲流.. – Jaiwo99

回答

0

嘗試使用下面的代碼來訪問文件ressources彈簧文件夾boot

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

你可以使用ClassPathResource

水木清華這樣的:

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

或者

File file = new ClassPathResource("schema.graphql").getFile(); 
相關問題