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

2020-08-06  本文已影响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
   private static File to(MultipartFile multipartFile) throws IOException {
        //创建目标文件
        File file = new File("/Users/xxx/" + multipartFile.getOriginalFilename());
        multipartFile.transferTo(file);
        return 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对象的

上一篇 下一篇

猜你喜欢

热点阅读