目 录CONTENT

文章目录

获取类路径某个json文件中的内容字符串

在水一方
2022-07-28 / 0 评论 / 0 点赞 / 507 阅读 / 1,438 字 / 正在检测是否收录...

前言

实际项目中可能会有需要读取类路径下面的配置文件中的内容的需求,由于springboot项目打包的是jar包,通过文件读取获取流的方式开发的时候没有问题,但是上到linux服务器上就有问题了,对于这个问题记录一下处理的方式

类加载器的方式

通过类加载器读取文件流,类加载器可以读取jar包中的编译后的class文件,当然也是可以读取jar包中的文件流了

比如要读取resources目录下common/tianyanchasearch.json这个文件

  String resourcePath = "common/tianyanchasearch.json";
  String content = FileUtil.getStringFromInputStream(resourcePath);
return GlobalResult.succeed(JSON.parseObject(content));


    /**
     * 从输入流中获取文件内容字符串
     * @param resourcePath
     * @return
     */
    public static String getStringFromInputStream(String resourcePath) {
        StringBuilder jsonString = new StringBuilder();
            BufferedReader bufferedReader = null;
            try {
                ClassPathResource classPathResource = new ClassPathResource(resourcePath);
                InputStream inputStream = classPathResource.getStream();
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream,StandardCharsets.UTF_8));
                char[] chars = new char[8192];
                int length;
                while ((length = bufferedReader.read(chars)) != -1) {
                    String temp = new String(chars, 0, length);
                    jsonString.append(temp);
                }
            } catch (IOException e) {
                System.out.println("=====获取数据异常=====" + e);
            } finally {
                if (null != bufferedReader) {
                    try {
                        bufferedReader.close();
                    } catch (IOException ex) {
                        System.out.println("=======获取数据时,关闭流异常=======" + ex);
                    }
                }
            }
        return jsonString.toString();
    }

ResourceUtils

File file = ResourceUtils.getFile("classpath:files/test.xlsx");
InputStream inputStream = new FileInputStream(file);

这种方式只有开发环境时可以读取到,生产环境读取失败。
推测主要原因是springboot内置tomcat,打包后是一个jar包,因此通过文件读取获取流的方式行不通,因为无法直接读取压缩包中的文件,读取只能通过流的方式读取

0

评论区