读取文件--ClassPathResource
- 前言
 - 一、使用ClassPathResource.getFile()的坑
 - 二、通过流读取文件内容
 - 总结
 
前言
需求:拿到一个小程序的皮肤文件夹,放在resource目录下
 1:根据皮肤的style.json,获取json内的${xxx.png}变量(获的图片名list)
 2:将图片上传图片库,用图片id替换变量
 3:生成后的style.json放入缓存中
这里记录下:ClassPathResource的使用中遇到的坑
 文件目录如下:
 
一、使用ClassPathResource.getFile()的坑
        ClassPathResource classPathResource = new ClassPathResource("/skins");
        File file = classPathResource.getFile();
        String[] list = file.list();
 
这个写法是为了:获取skins文件夹下所有的文件名
本地结果是:
["doodle","standard","skinCode.json"]
 
坑来了:
本地启动是正常的,但是将项目发到服务器上,报错了:
 class path resource [skins] cannot be resolved to absolute file path because it。
这是为啥呢?
 因为文件在jar包里,直接通过文件资源路径是拿不到文件的。 可以用文件流去获取
二、通过流读取文件内容
json文件转为jsonObject
        ClassPathResource classPathResource = new ClassPathResource(SKINS + SKIN_CODE_DIR + JSON_FILE);
        InputStream inputStream = classPathResource.getInputStream();
        JSONObject json = JSONObject.parseObject(inputStream, JSONObject.class);
 
图片转为byte[]
        InputStream inputStream = new ClassPathResource(filePath).getInputStream();
        byte[] bytes = IOUtils.toByteArray(inputStream);
 
如果需要返回文件给前端,也可以通过HttpServletResponse返出去
总结
吃了技术差的苦啊



















