文件处理工具类

一、引入依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.30</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

二、FileUtils工具类 

package com.hl.redisdemo.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Objects;

/**
 * 文件处理工具类
 *
 * @author hulei
 */
@Slf4j
public class FileUtils {

    /**
     * 获得指定文件的byte数组
     *
     * @param filePath 文件路径
     * @return 字节数组
     */
    public static byte[] fileToByte(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            buffer = getBytes(file);
        } catch (Exception e) {
            log.error("根据文件路径加载文件转字节数组失败:{}", e.getMessage(), e);
        }
        return buffer;
    }

    private static byte[] getBytes(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
        byte[] b = new byte[1024];
        int n;
        while ((n = fis.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        fis.close();
        bos.close();
        return bos.toByteArray();
    }

    /**
     * @param multipartFile 真实文件
     * @return byte[] 数组
     */
    public static byte[] multipartFileToByte(MultipartFile multipartFile) throws Exception {
        byte[] buffer = null;
        File file = multipartFileToFile(multipartFile);
        try {
            buffer = getBytes(file);
        } catch (Exception e) {
            log.error("真实文件转字节数组失败:{}", e.getMessage(), e);
        } finally {
            //清除缓存文件
            deleteTempFile(file);
        }
        return buffer;
    }


    /**
     * 根据byte数组,生成文件
     *
     * @param bfile    字节数组
     * @param filePath 文件路径
     * @param fileName 文件名
     */
    public static void byteToFile(byte[] bfile, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {
                boolean mkDirs = dir.mkdirs();
                log.info("创建目录结果:{}",mkDirs);
            }
            file = new File(filePath + "\\" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            log.error("根据byte数组,生成文件失败:{}", e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(fos);
        }
    }

    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (!file.isEmpty()) {
            InputStream ins;
            ins = file.getInputStream();
            toFile = new File(Objects.requireNonNull(file.getOriginalFilename()));
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        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, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            log.error("输入流生成文件失败:{}", e.getMessage(), e);
        }
    }

    /**
     * 删除临时文件
     * @param file 文件
     */
    public static void deleteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            boolean delete = del.delete();
            log.info("删除文件结果:{}",delete);
        }
    }
}

三、代码分析

这段代码是一个名为FileUtils的Java类,它包含了一系列静态方法,用于处理文件和字节操作。以下是主要功能的分析:
文件转字节数组:
       fileToByte方法接收一个文件路径,读取文件内容并返回字节数组。
       getBytes方法是fileToByte的辅助方法,使用FileInputStream和ByteArrayOutputStream读取文件。

MultipartFile转字节数组:
       multipartFileToByte方法接收一个MultipartFile对象,将其内容转换为字节数组。转换后,它还会删除临时文件。

字节数组转文件:
       byteToFile方法将字节数组写入到指定路径和文件名的文件中。它首先检查并创建目标目录,如果必要。

MultipartFile转本地文件:
       multipartFileToFile方法接收一个MultipartFile对象,创建一个临时文件并写入内容。返回这个临时文件对象。

输入流转文件:
       inputStreamToFile方法从给定的InputStream读取数据并写入到指定的File对象中。

删除文件:
        deleteTempFile方法删除给定的File对象代表的文件。

整个类使用了Lombok库的@Slf4j注解,提供了日志记录功能。在每个可能抛出异常的方法中,都使用了异常处理来记录错误信息。此外,代码中使用了Apache Commons IO库的IOUtils类来关闭流。 

  • 21
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值