※JAVA获取资源文件内容※

Posted zhuo-zui

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了※JAVA获取资源文件内容※相关的知识,希望对你有一定的参考价值。

※使用ResourceUtils工具类(基于GraphQL查询):

 1 package cn.itcast.haoke.dubbo.api.graphql;
 2 
 3 import cn.itcast.haoke.dubbo.server.service.HouseResourcesService;
 4 import graphql.GraphQL;
 5 import graphql.schema.GraphQLSchema;
 6 import graphql.schema.idl.RuntimeWiring;
 7 import graphql.schema.idl.SchemaGenerator;
 8 import graphql.schema.idl.SchemaParser;
 9 import graphql.schema.idl.TypeDefinitionRegistry;
10 import org.springframework.beans.factory.annotation.Autowired;
11 import org.springframework.context.annotation.Bean;
12 import org.springframework.stereotype.Component;
13 import org.springframework.util.ResourceUtils;
14 
15 import javax.annotation.PostConstruct;
16 import java.io.File;
17 import java.io.IOException;
18 
19 @Component
20 public class GraphQLProvider {
21     private GraphQL graphQL;
22     @Autowired
23     private HouseResourcesService houseResourcesService;
24     @PostConstruct
25     public void init() throws IOException{
26         File file = ResourceUtils.getFile("classpath:haoke.graphqls");
27         GraphQLSchema graphQLSchema = buildSchema(file);
28         this.graphQL = GraphQL.newGraphQL(graphQLSchema).build();
29     }
30     private GraphQLSchema buildSchema(File file){
31         TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(file);
32         RuntimeWiring runtimeWiring = buildWiring();
33         SchemaGenerator schemaGenerator = new SchemaGenerator();
34         return schemaGenerator.makeExecutableSchema(typeRegistry,runtimeWiring);
35     }
36     private RuntimeWiring buildWiring(){
37         return RuntimeWiring.newRuntimeWiring().type("HaokeQuery",builder->builder.dataFetcher("HouseResources"
38                 ,enviroment->{
39             Long id = enviroment.getArgument("id");
40             return this.houseResourcesService.queryHouseResourcesById(id);
41                 })).build();
42     }
43     @Bean
44     public GraphQL graphQL(){
45         return graphQL;
46     }
47 }

※使用类加载器,并利用工具包转为字符串:

import org.apache.commons.io.IOUtils;

/*读取文件内容*/
    public static String readFileToString(String fileName){
        try {
            return IOUtils.toString(GraphQLSchema.class.getClassLoader().getResourceAsStream(fileName),"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

以上是关于※JAVA获取资源文件内容※的主要内容,如果未能解决你的问题,请参考以下文章

※JAVA获取资源文件内容※

java读取资源文件(Properties)

如何获取项目src目录下的资源文件

如何在 Java JAR 文件中获取资源的路径

这是从片段中获取字符串资源的正确方法吗?

从 XML 声明片段获取 XML 编码:部分内容解析不支持 XmlDeclaration