Java ClassPathResource 读取JAR包中的资源

叙述

使用 ClassPathResource类 读取 jar 包中的资源文件。自测100%可用。

环境

要读取 resources 目录下的 JSON 文件,如图:

                        

包完整路径:

org.springframework.core.io

代码

/**
     * 读取json文件,返回json串
     */
    private String readJsonFile() {
        BufferedReader reader = null;
        String content = "";

        try {
            ClassPathResource resource = new ClassPathResource("unitMapping.json");
            reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
            content = reader.lines().collect(Collectors.joining("\n"));
            reader.close();
        } catch (Exception e) {
            logger.error("接口【DictionaryService getUnitMapping】异常参数:" + e);
        } finally {
            try {
                if (null != reader) {
                    reader.close();
                }
            } catch (IOException e) {
                logger.error("接口【DictionaryService getUnitMapping】异常参数:" + e);
            }
        }

        return content;
    }

测试

发布了22 篇原创文章 · 获赞 30 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/lizhengyu891231/article/details/103783900