【Java】File和MultipartFile互转,文件压缩解压工具类

概述

Java工具类实现File和MultipartFile互转,文件压缩解压功能。


1.File和MultipartFile互转

import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.Files;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtil {
    /**
     * 将 File 转换为 MultipartFile。
     *
     * @param file      要转换的文件
     * @param fieldName 字段名,通常用于表单中的文件字段名
     * @return 转换后的 MultipartFile
     * @throws IOException 如果发生I/O错误
     */
    public static MultipartFile fileToMultipartFile(File file, String fieldName) throws IOException {
        try {
            if (file == null || !file.exists()) {
                throw new FileNotFoundException("文件未找到:" + file);
            }
            byte[] content = Files.readAllBytes(file.toPath());
            return new ByteArrayMultipartFile(content, file.getName(), fieldName, Files.probeContentType(file.toPath()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 删除临时文件
            file.delete();
        }
    }
 
    /**
     * 将 MultipartFile 转换为 File。
     *
     * @param multipartFile 要转换的 MultipartFile
     * @return 转换后的 File
     * @throws IOException 如果发生I/O错误
     */
    public static File multipartFileToFile(MultipartFile multipartFile) throws IOException {
        if (multipartFile.isEmpty()) {
            throw new IOException("传入的MultipartFile为空");
        }
        String originalFilename = multipartFile.getOriginalFilename();
        String tempFileSuffix = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf('.')) : ".tmp";
        File tempFile = File.createTempFile("temp", tempFileSuffix);
        try (InputStream ins = multipartFile.getInputStream();
             OutputStream os = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = ins.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        }
        return tempFile;
    }
 
    /**
     * 内置一个简单的 MultipartFile 实现类,用于File转换
     */
    private static class ByteArrayMultipartFile implements MultipartFile {
        private final byte[] content;
        private final String name;
        private final String originalFilename;
        private final String contentType;
 
        /**
         * 构造函数
         *
         * @param content         文件内容
         * @param originalFilename 文件原始名字
         * @param name            字段名
         * @param contentType     文件类型
         */
        public ByteArrayMultipartFile(byte[] content, String originalFilename, String name, String contentType) {
            this.content = content;
            this.originalFilename = originalFilename;
            this.name = name;
            this.contentType = contentType;
        }
 
        @Override
        public String getName() {
            return this.name;
        }
 
        @Override
        public String getOriginalFilename() {
            return this.originalFilename;
        }
 
        @Override
        public String getContentType() {
            return this.contentType;
        }
 
        @Override
        public boolean isEmpty() {
            return (this.content == null || this.content.length == 0);
        }
 
        @Override
        public long getSize() {
            return this.content.length;
        }
 
        @Override
        public byte[] getBytes() {
            return this.content;
        }
 
        @Override
        public InputStream getInputStream() {
            return new ByteArrayInputStream(this.content);
        }
 
        @Override
        public void transferTo(File dest) throws IOException, IllegalStateException {
            try (OutputStream os = new FileOutputStream(dest)) {
                os.write(this.content);
            }
        }
    }
 
}

测试类

public class ZipExample {
    public static void main(String[] args) throws IOException {

        File file = new File("C:\\Users\\Administrator\\Desktop\\output.zip");
        MultipartFile fileToMultipartFile = FileUtil.fileToMultipartFile(file, file.getName());

        MultipartFile multipartFile = getMultipartFile(); // 这个方法是假设的,你需要根据实际情况获取 MultipartFile
        File toFile = FileUtil.multipartFileToFile(multipartFile);
    }
}

2.文件压缩、解压

import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipFile;


public class ZipUtil {

    public static void doCompress(String srcFile, String zipFile) throws IOException {
        doCompress(new File(srcFile), new File(zipFile));
    }

    /**
     * 文件压缩
     * @param srcFile 目录或者单个文件
     * @param zipFile 压缩后的ZIP文件
     */
    public static void doCompress(File srcFile, File zipFile) throws IOException {
        ZipOutputStream out = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(zipFile));
            doCompress(srcFile, out);
        } catch (Exception e) {
            throw e;
        } finally {
            out.close();//记得关闭资源
        }
    }

    public static void doCompress(String filelName, ZipOutputStream out) throws IOException{
        doCompress(new File(filelName), out);
    }

    public static void doCompress(File file, ZipOutputStream out) throws IOException{
        doCompress(file, out, "");
    }

    public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
        if ( inFile.isDirectory() ) {
            File[] files = inFile.listFiles();
            if (files!=null && files.length>0) {
                for (File file : files) {
                    String name = inFile.getName();
                    if (!"".equals(dir)) {
                        name = dir + "/" + name;
                    }
                    FileUtil.doCompress(file, out, name);
                }
            }
        } else {
            FileUtil.doZip(inFile, out, dir);
        }
    }

    public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
        String entryName = null;
        if (!"".equals(dir)) {
            entryName = dir + "/" + inFile.getName();
        } else {
            entryName = inFile.getName();
        }
        ZipEntry entry = new ZipEntry(entryName);
        out.putNextEntry(entry);

        int len = 0 ;
        byte[] buffer = new byte[1024];
        FileInputStream fis = new FileInputStream(inFile);
        while ((len = fis.read(buffer)) > 0) {
            out.write(buffer, 0, len);
            out.flush();
        }
        out.closeEntry();
        fis.close();
    }

    public static void unzipByPath(String zipFilePath, String destDir) {
        File dir = new File(destDir);
        if (!dir.exists()) dir.mkdirs(); // 创建目标目录

        try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(Paths.get(zipFilePath)))) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                File newFile = new File(destDir, entry.getName());
                if (entry.isDirectory()) {
                    newFile.mkdirs(); // 创建目录
                } else {
                    // 创建文件
                    new File(newFile.getParent()).mkdirs();
                    try (FileOutputStream fos = new FileOutputStream(newFile)) {
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                    }
                }
                zis.closeEntry();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void unZip(File srcFile,String destDirPath){
        long start = System.currentTimeMillis();
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");

        }
        // 开始解压
        ZipFile zipFile = null;

        try {
            zipFile = new ZipFile(srcFile);
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                System.out.println("解压" + entry.getName());

                // 如果是文件夹,就创建个文件夹
                if (entry.isDirectory()) {
                    String dirPath = destDirPath + "/" + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();

                } else {
                    // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    // 保证这个文件的父文件夹必须要存在
                    if(!targetFile.getParentFile().exists()){
                        targetFile.getParentFile().mkdirs();

                    }
                    targetFile.createNewFile();

                    // 将压缩文件内容写入到这个文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[1024];

                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);

                    }
                    // 关流顺序,先打开的后关闭
                    fos.close();
                    is.close();
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("解压完成,耗时:" + (end - start) +" ms");

        } catch (Exception e) {
            throw new RuntimeException("unzip error from ZipUtils", e);
        } finally {
            if(zipFile != null){
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
}

测试类

public class ZipExample {
    public static void main(String[] args) throws IOException {

        String sourcePath = "C:\\Users\\Administrator\\Desktop\\模板文件";              // 原文件路径
        String zipFilePath = "C:\\Users\\Administrator\\Desktop\\output.zip";         // 压缩文件路径
        ZipUtil.doCompress(sourcePath, zipFilePath);
        System.out.println("压缩完成,生成的ZIP文件在:" + zipFilePath);


        File sourefile = new File("C:\\Users\\Administrator\\Desktop\\模板文件");         // 原文件
        File zipFile = new File("C:\\Users\\Administrator\\Desktop\\output.zip");       // 压缩文件
        ZipUtil.doCompress(sourefile, zipFile);
        System.out.println("压缩完成,生成的ZIP文件在:" + zipFile.getAbsolutePath());


        File unzipSourefile = new File("C:\\Users\\Administrator\\Desktop\\模板文件");   // 原压缩文件
        String destPath = "C:\\Users\\Administrator\\Desktop\\test";                            // 解压路径
        ZipUtil.unZip(unzipSourefile,destPath);
        System.out.println("解压成功!解压后的文件在:" + destPath);


        String unzipFilePath = "C:\\Users\\Administrator\\Desktop\\output.zip";     // 压缩文件路径
        String dest = "C:\\Users\\Administrator\\Desktop\\test";                    // 解压路径
        ZipUtil.unzipByPath(unzipFilePath,dest);
        System.out.println("解压成功!解压后的文件在:" + dest);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值