一、引入依赖
<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);}}
}