美文网首页
Springboot读取Resource资源文件并转化为Mult

Springboot读取Resource资源文件并转化为Mult

作者: 李念阳 | 来源:发表于2020-08-06 09:57 被阅读0次
项目结构:
image.png
1、读取单个文件
Resource resource = new ClassPathResource("data/test1.sh");
2、读取多个文件
  • 所有文件
 Resource[] resources = new PathMatchingResourcePatternResolver().getResources("data/*.*");
  • 后缀匹配
 Resource[] resources = new PathMatchingResourcePatternResolver().getResources("data/*.sh");
3、转化为MultipartFile

需要引入依赖

compile("org.springframework:spring-test:5.2.4.RELEASE")
public static void single() throws IOException {
        Resource resource = new ClassPathResource("data/test1.sh");
        String fileName = resource.getFilename();
        String fileNameNoExtension = getFileNameNoExtension(fileName);
        InputStream inputStream = resource.getInputStream();
        MultipartFile multipartFile =  new MockMultipartFile(fileNameNoExtension, fileName, "text/plain", inputStream);
    }

public static String getFileNameNoExtension(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }
4、转化为File
  • 可以通过MultipartFile转化为File
   private static File to(MultipartFile multipartFile) throws IOException {
        //创建目标文件
        File file = new File("/Users/xxx/" + multipartFile.getOriginalFilename());
        multipartFile.transferTo(file);
        return file;
    }
  • 直接将resource转成file
 public static File to(Resource resource) throws IOException {
        File file = new File("/Users/linianyang/" + resource.getFilename());
        InputStream inputStream = resource.getInputStream();
        OutputStream os = new FileOutputStream(file);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        inputStream.close();
        return file;
    }

!!!!千万不可以直接执行resource.getFile(),在生产环境下是获取不到File对象的

相关文章

网友评论

      本文标题:Springboot读取Resource资源文件并转化为Mult

      本文链接:https://www.haomeiwen.com/subject/bzdbchtx.html