文件操作工具类封装

本文介绍了一个实用的文件操作工具类,重点在于实现Base64字符串与图片之间的相互转换。该工具类提供了从Base64字符串转换为图片文件以及从图片文件转换为Base64字符串的方法,适用于Spring Boot项目中的图片处理需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.springboot.mobile.imagecenter.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;

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

/**
 * @author maniac
 * date:2019/07/13 14:11
 * @do 用于文件读写及操作的工具类
 * 工具类的使用原则 尽量不要在封装的工具类出现: 非文件相关的出入参
 */
@Slf4j
public class FileUtil {
    /**
     * base64字符串转化成图片
     * @param baseStr  图片的base64 字符串
     * @param filePath 文件目录
     * @param fileName 图片名
     * @return  图片的路径: 文件目录+图片名 返回结果为空串则出现异常
     */
    public static String base64ToImage(String baseStr, String filePath,String fileName) {
        byte[] bytes = null;
        try {
            bytes = Base64Utils.decodeFromString(baseStr);
        }catch (Exception e){
            log.error("【文件转换操作】base64码转字节数组出现异常,文件名为:{},e:",(filePath+"/"+fileName),e);
            return "";
        }
        if (Objects.nonNull(bytes)&&0==bytes.length){
            return "";
        }
        return byteToFile(bytes, filePath, fileName);
    }
    /**
     * 图片转base64字符串
     *
     * @param path 图片的路径: 文件目录+图片名
     * @return base64 字符串 字符串为空串则出现异常
     */
    public static String imageToBase64(String path) {
        byte[] imageBytes = fileToByte(path);
        if (0 == imageBytes.length) {
            return "";
        }
        //对字节数组进行base64编码
        return Base64Utils.encodeToString(imageBytes);
    }

    /**
     * 把字节码文件写入到指定的路径
     * 注:默认转换字节数组大小为1KB,输出缓存区大小为 8Kb
     *
     * @param bytes    字节码数组
     * @param filePath 文件目录
     * @param fileName 文件名
     * @return 成功返回 文件全路径 失败返回空串
     */
    public static String byteToFile(byte[] bytes, String filePath, String fileName) {
        int bufferSize = 1024;//转化字符数组 默认大小1KB
        int bufferSizeOut = 8192;//BufferedOutputStream 默认缓冲区大小
        return byteToFile(bytes, filePath, fileName, bufferSize, bufferSizeOut);
    }

    /**
     * 读取指定路径的文件(默认输入缓冲区的大小1KB)
     * 注:默认转换字节数组大小为1KB,输入缓存区大小为 8Kb
     *
     * @param filePath 文件路径
     * @return 字节码数组  说明:字节码数组为0 则发生异常
     */
    public static byte[] fileToByte(String filePath) {
        int bufferSize = 1024;//转化字符数组 默认大小1KB
        int bufferSizeIn = 8192;//BufferedInputStream 默认缓冲区大小
        return fileToByte(filePath, bufferSize, bufferSizeIn);
    }

    /**
     * 把字节码文件写入到指定的路径
     *
     * @param bytes         字节码数组
     * @param filePath      文件目录
     * @param fileName      文件名
     * @param bufferSize    转换字节数组大小(可定制)
     * @param bufferSizeOut 输出缓存区大小(可定制)
     * @return 成功返回 文件全路径 失败返回空串
     */
    private static String byteToFile(byte[] bytes, String filePath, String fileName, int bufferSize, int bufferSizeOut) {
        File dir = new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {//判断文件目录是否存在
            boolean mkdirs = dir.mkdirs();
            if (mkdirs) {
                log.debug("【文件操作】文件路径创建成功,folerPath:{}", filePath);
            }
        }
        String path = filePath +"/"+ fileName;
        File file = new File(path);
        try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file), bufferSizeOut)) {
            byte[] buffer = new byte[bufferSize];
            int len = 0;
            while (-1 != (len = bais.read(buffer, 0, bufferSize))) {
                bos.write(buffer, 0, len);
            }
            bos.flush();
            return path;
        } catch (Exception e) {
            log.error("【数据流操作】文件写入指定路径异常,文件的路径为:{},e:", (filePath +"/"+ fileName), e);
            return "";
        }
    }

    /**
     * 读取指定路径的文件到字节数组
     *
     * @param filePath     文件路径
     * @param bufferSize   转换字节数组大小(可定制)
     * @param bufferSizeIn 输入缓存区大小(可定制)
     * @return 字节码数组  说明:字节码数组为byte[0] 则发生异常
     */
    private static byte[] fileToByte(String filePath, int bufferSize, int bufferSizeIn) {
        File file = new File(filePath);
        //判断文件路径是否存在
        if (!file.exists()) {
            log.info("【数据流操作】文件路径不存在,filePath:{}", filePath);
            return new byte[0];
        }
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream((int) file.length());
             BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file), bufferSizeIn)) {
            byte[] buffer = new byte[bufferSize];
            int len = 0;
            while (-1 != (len = bis.read(buffer, 0, bufferSize))) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            return baos.toByteArray();
        } catch (Exception e) {
            log.error("【数据流操作】读取指定路径文件异常,filePath:{},e:", filePath, e);
            return new byte[0];
        }
    }
    private FileUtil() {
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值