multipartFileToFile转file以及相关操作工具类

文件转换、更换流文件、重新启动服务器时自动删除缓存文件

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class FileUtils {

    /**
     * MultipartFile 转换成 File
     * @param file 要转换的 MultipartFile
     * @return 转换后的 File
     * @throws Exception 可能抛出的异常
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.isEmpty() || file.getSize() <= 0) {
            return null;
        }
        try (InputStream ins = file.getInputStream()) {
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            toFile.deleteOnExit();
        }
        return toFile;
    }

    /**
     * 获取流文件
     * @param ins 输入流
     * @param file 目标文件
     */
    private static void inputStreamToFile(InputStream ins, File file) {
        try (OutputStream os = new FileOutputStream(file)) {
            int bytesRead;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件
     * @param file 要删除的文件
     * @return 删除是否成功
     */
    public static boolean deleteFile(File file) {
        if (file != null && file.exists()) {
            return file.delete();
        }
        return false;
    }

    /**
     * 复制文件
     * @param sourceFile 源文件
     * @param destFile 目标文件
     * @return 复制是否成功
     */
    public static boolean copyFile(File sourceFile, File destFile) {
        if (!sourceFile.exists()) {
            return false;
        }
        try (InputStream in = new FileInputStream(sourceFile);
             OutputStream out = new FileOutputStream(destFile)) {
            byte[] buffer = new byte[8192];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取文件扩展名
     * @param file 文件
     * @return 文件扩展名
     */
    public static String getFileExtension(File file) {
        String fileName = file.getName();
        int lastIndex = fileName.lastIndexOf('.');
        if (lastIndex != -1 && lastIndex < fileName.length() - 1) {
            return fileName.substring(lastIndex + 1);
        }
        return "";
    }
}    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

boJIke

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值