windows环境和linux环境下获取文件路径名并读取文件内容

windows环境和linux环境下获取文件路径名并读取文件内容

在编写代码时我们经常会发生明明测试环境没问题,但是到线上生产环境中就出bug,这是因为我们常常在本地环境与线上环境文件存放的路径不一致,这里我们直接获取Resource下资源文件windows的与linux的文件分隔符"\"是不一样的这样会导致文件路径不存在的错误产生我们要用 File.separator替代

 {String filePath = this.getClass().getResource("/").getPath() + "file" + File.separator + "json";

 			//获得target下的资源文件
            File file = ResourceUtils.getFile(filePath);
            List<String> fileNames = new ArrayList<>();
            File[] files = file.listFiles();

这段代码在springboot打包成jar包后无法根据File访问jar包里面的路径修改成以下:
}

     List<String> fileNames = new ArrayList<>();
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("classpath:file/json".concat("/*"));

            for (Resource resource : resources) {
                fileNames.add(resource.getFilename());
            }
            if(files.length>0){
                Arrays.stream(files).forEach(fileName -> {
                    fileNames.add(fileName.getName());
                });
                if (fileNames.size() > 0) {
                    // 解析文件数据
                    for (String fileName : fileNames) {
               			//拿到文件名后,ClassPathResource 拼写文件所在的Resource路径名
                        String filePathRelative= "file" + File.separator + "json" + File.separator + fileName;
                        //用classPathResource获取文件并以流的方式读取出来写入字节流
                        ClassPathResource classPathResource = new ClassPathResource(filePathRelative);
                        InputStream inputStream = classPathResource.getInputStream();
                        ByteArrayOutputStream result = new ByteArrayOutputStream();
                        while ((length = inputStream.read(buffer)) != -1) {
                            result.write(buffer, 0, length);
                        }
                        //将字节流转换成json文件
                        JSONObject jsonObject = JSONObject.parseObject(result.toString(StandardCharsets.UTF_8.name()));
                     
                    }

                }
            }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值