读取resource路径下面的json文件


    @Test
    public void test01() {
        JSONArray jsonObjFromResource = getJsonObjFromResource("/face.json");
        System.out.println(jsonObjFromResource);
    }
    public JSONArray getJsonObjFromResource(String filename) {
        JSONArray json = null;

        if (!filename.contains(".json")) {
            filename += ".json";
        }

        try {
            InputStream inputStream = getClass().getResourceAsStream(filename);
            if (inputStream != null) {
                StringBuilder sb = new StringBuilder();
                InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
                BufferedReader bfReader = new BufferedReader(reader);
                String content = null;
                while ((content = bfReader.readLine()) != null) {
                    sb.append(content);
                }
                bfReader.close();
                json = JSON.parseArray(sb.toString());
            } else {
                log.info("[{}] file not exist", filename);
            }

        } catch (Exception e) {
            log.error("read file to string error", e);
        }

        return json;
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在SpringBoot应用程序中读取jar文件外的JSON文件,可以使用ResourceLoader和File类。以下是一种可能的实现方式: 1. 首先,创建一个ResourceLoader bean,用于加载外部资源文件。可以在应用程序启动时通过@Configuration注解将其添加到Spring上下文中: ``` @Configuration public class AppConfig { @Bean public ResourceLoader resourceLoader() { return new DefaultResourceLoader(); } } ``` 2. 在需要读取JSON文件的类中注入ResourceLoader bean,并使用其getResource()方法获取文件Resource对象: ``` @Autowired private ResourceLoader resourceLoader; public void readJsonFile() { Resource resource = resourceLoader.getResource("file:/path/to/file.json"); File file = resource.getFile(); // Do something with the file } ``` 3. 注意,getFile()方法返回的是一个本地文件对象,因此需要确保应用程序有足够的权限来访问该文件。可以使用file:前缀指定文件路径,也可以使用classpath:前缀指定类路径下的文件。 4. 也可以使用InputStream来读取JSON文件。可以使用Resource对象的getInputStream()方法获取输入流: ``` public void readJsonFile() throws IOException { Resource resource = resourceLoader.getResource("file:/path/to/file.json"); InputStream inputStream = resource.getInputStream(); // Do something with the input stream } ``` 5. 最后,可以使用Jackson库将JSON数据转换为Java对象,或者使用JsonNode类解析JSON数据。可以在pom.xml文件中添加以下依赖项来包含Jackson库: ``` <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.4</version> </dependency> ``` 以上是一种简单的方法来读取jar文件外的JSON文件。如果需要在应用程序中频繁读取外部文件,可以考虑使用缓存来提高性能。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值