Чтение файла доступно в папке ресурсов с SpringBoot
Я собираюсь прочитать файл, доступный в папке ресурсов в моем приложении 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();
Кто-нибудь может помочь мне разобраться с этим
3 ответа
Вы можете использовать ClassPathResource
Что-то вроде этого:
InputStream inputStream = new ClassPathResource("schema.graphql").getInputStream();
Или же
File file = new ClassPathResource("schema.graphql").getFile();
Попробуйте использовать код ниже для доступа к файлам в папке ресурсов с весенней загрузкой
File file = new ClassPathResource("schema.graphql").getFile();
Добавление ответа отсюда , Доступ к
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();
}