java文件工具类
package codeAssistant.util;
import codeAssistant.enums.BaseEnum;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author: yc
* @des: 文件工具类
* @date: 2023/8/29 10:49
*/
public class FileUtils {
/**
* .
*/
private final static String DOT = ".";
/**
* /
*/
private final static String SLASH = "/";
/**
* ""
*/
private final static String EMPTY_STR = "";
/**
* _
*/
private final static String UNDERLINE = "_";
/**
* 本地存储路径 可从配置文件中读取
*/
private static String LOCAL_FILE_SAVE_PATH = "D:/code/fileStore";
/**
* 初始化本地存储路径
*/
static {
try {
YamlPropertiesFactoryBean yamlPropertySourceFactory = new YamlPropertiesFactoryBean();
yamlPropertySourceFactory.setResources(new ClassPathResource("application.yml"));
Properties properties = yamlPropertySourceFactory.getObject();
LOCAL_FILE_SAVE_PATH = properties.getProperty("filestore.path");
}catch (Exception e){
}
}
/**
* @author: yc
* @des: 文件上传到本地
* dirName1 一级目录名称
* dirName2 二级目录名称
* mode 前缀模式 TIMESTAMP(时间戳) UUID(uuid) NONE (无需随机前缀)
* @date: 2024/06/07 16:13
*/
public static Map<String,String> upload2local(MultipartFile multipartFile, String dirName1, String dirName2, FilePixModeEnum filePixModeEnum){
Map<String,String> map = new HashMap<>();
String originalFilename = multipartFile.getOriginalFilename();
// 拿到文件后缀
String fileSuffix = getFileSuffix(originalFilename);
if(!filePixModeEnum.equals(FilePixModeEnum.NONE)){
originalFilename = originalFilename.replace(DOT + fileSuffix,"");
}
if(filePixModeEnum.equals(FilePixModeEnum.TIMESTAMP)){
originalFilename = originalFilename + UNDERLINE + getTimestampNow() + DOT + fileSuffix;
}else if(filePixModeEnum.equals(FilePixModeEnum.UUID)){
originalFilename = originalFilename + UNDERLINE + UUID.randomUUID() + DOT + fileSuffix;
}
// 本地文件绝对路径
StringBuilder stringBuilder = new StringBuilder();
if(StringUtils.isNotBlank(dirName1)){
stringBuilder.append(SLASH).append(dirName1);
}
if(StringUtils.isNotBlank(dirName2)){
stringBuilder.append(SLASH).append(dirName2);
}
String path = stringBuilder.append(SLASH).append(getYMD("yyyy/MM/dd")).toString();
// 全路径
String allPath = LOCAL_FILE_SAVE_PATH + path;
mkdir(allPath);
// 绝对路径
String absolutePath = allPath + SLASH + originalFilename;
// 将文件存储到路径中
try {
multipartFile2file(multipartFile,absolutePath);
}catch (Exception e){
System.out.println(e.getMessage());
}
// 相对路径
path = path + SLASH + originalFilename;
map.put("fileName",originalFilename);
map.put("fileSize",String.valueOf(multipartFile.getSize()));
map.put("filePath",path);
map.put("dirName1",dirName1);
map.put("dirName2",dirName2);
return map;
}
/**
* @author: yc
* @des: 文件上传到本地
* dirName1 一级目录名称
* dirName2 二级目录名称
* mode 前缀模式 TIMESTAMP(时间戳) UUID(uuid) NONE (无需随机前缀)
* needYMD 是否需要年/月/日 子目录
* @date: 2024/06/07 16:13
*/
public static Map<String,String> upload2local(MultipartFile multipartFile, String dirName1, String dirName2, FilePixModeEnum filePixModeEnum,Boolean needYMD){
Map<String,String> map = new HashMap<>();
String originalFilename = multipartFile.getOriginalFilename();
// 拿到文件后缀
String fileSuffix = getFileSuffix(originalFilename);
if(!filePixModeEnum.equals(FilePixModeEnum.NONE)){
originalFilename = originalFilename.replace(DOT + fileSuffix,"");
}
if(filePixModeEnum.equals(FilePixModeEnum.TIMESTAMP)){
originalFilename = originalFilename + UNDERLINE + getTimestampNow() + DOT + fileSuffix;
}else if(filePixModeEnum.equals(FilePixModeEnum.UUID)){
originalFilename = originalFilename + UNDERLINE + UUID.randomUUID() + DOT + fileSuffix;
}
// 本地文件绝对路径
StringBuilder stringBuilder = new StringBuilder();
if(StringUtils.isNotBlank(dirName1)){
stringBuilder.append(SLASH).append(dirName1);
}
if(StringUtils.isNotBlank(dirName2)){
stringBuilder.append(SLASH).append(dirName2);
}
String path = Objects.isNull(needYMD) || !needYMD ? stringBuilder.toString() : stringBuilder.append(SLASH).append(getYMD("yyyy/MM/dd")).toString();
// 全路径
String allPath = LOCAL_FILE_SAVE_PATH + path;
mkdir(allPath);
// 绝对路径
String absolutePath = allPath + SLASH + originalFilename;
// 将文件存储到路径中
try {
multipartFile2file(multipartFile,absolutePath);
}catch (Exception e){
System.out.println(e.getMessage());
}
// 相对路径
path = path + SLASH + originalFilename;
map.put("fileName",originalFilename);
map.put("fileSize",String.valueOf(multipartFile.getSize()));
map.put("filePath",path);
map.put("dirName1",dirName1);
map.put("dirName2",dirName2);
return map;
}
/**
* @author: yc
* @des: 字符串写入文件
* @date: 2024/8/3 1:05
*/
public static Map<String,String> str2file(String str,String fileName,String type,String dirName1, String dirName2, FilePixModeEnum filePixModeEnum,Boolean needYMD){
if(Objects.isNull(str)){
return null;
}
return byte2file(str.getBytes(),fileName,type,dirName1,dirName2,filePixModeEnum,needYMD);
}
/**
* @author: yc
* @des: 图片写入文件
* @date: 2024/8/3 2:20
*/
public static Map<String,String> img2file(BufferedImage bufferedImage, String fileName, String type, String dirName1, String dirName2, FilePixModeEnum filePixModeEnum, Boolean needYMD){
ByteArrayOutputStream byteArrayOutputStream = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage,"png",byteArrayOutputStream);
}catch (Exception e){
System.out.println(e.getMessage());
return null;
}
return byte2file(byteArrayOutputStream.toByteArray(),fileName,type,dirName1,dirName2,filePixModeEnum,needYMD);
}
/**
* @author: yc
* @des: 字节写入文件
* @date: 2024/8/3 1:58
*/
public static Map<String,String> byte2file(byte[] bytes,String fileName,String type,String dirName1, String dirName2, FilePixModeEnum filePixModeEnum,Boolean needYMD){
if(Objects.isNull(bytes) || bytes.length <= 0){
return null;
}
return upload2local(byte2multipartFile(bytes,fileName,type),dirName1,dirName2,filePixModeEnum,needYMD);
}
/**
* @author: yc
* @des: 字节 转 MultipartFile
* @date: 2024/8/3 1:19
*/
public static MultipartFile byte2multipartFile(byte[] bytes,String fileName,String type){
File tempFile = byte2file(bytes);
MultipartFile multipartFile = file2multipartFile(tempFile, fileName, type);
tempFile.delete();
return multipartFile;
}
/**
* @author: yc
* @des: 字节转文件
* @date: 2024/8/3 1:23
*/
public static File byte2file(byte[] bytes){
File file = null;
try {
file = File.createTempFile("file",".bin");
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(bytes);
fileOutputStream.flush();
fileOutputStream.close();
}catch (Exception e){
System.out.println(e.getMessage());
}
return file;
}
/**
* @author: yc
* @des: File转为MultipartFile
* @date: 2024/04/08 14:34
*/
public static MultipartFile file2multipartFile(File file, String fileName,String type) {
FileItem item = new DiskFileItemFactory().createItem("file", type, false,fileName + type);
try (InputStream inputStream = new FileInputStream(file);
OutputStream outputStream = item.getOutputStream()) {
inputStream2outputStream(inputStream,outputStream);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return new CommonsMultipartFile(item);
}
/**
* @author: yc
* @des: MultipartFile转为File
* @date: 2024/08/02 16:41
*/
public static File multipartFile2file(MultipartFile multipartFile,String path){
File file = null;
try {
file = new File(path);
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(multipartFile.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
}catch (Exception e){
System.out.println(e.getMessage());
}
return file;
}
/**
* @author: yc
* @des: 创建文件夹
* @date: 2024/08/02 17:22
*/
public static Boolean mkdir(String path){
File file = new File(path);
return file.exists() ? Boolean.TRUE : file.mkdirs();
}
/**
* @author: yc
* @des: 根据文件名获取文件后缀名
* @date: 2024/8/2 23:22
*/
public static String getFileSuffix(String fileName){
if(Objects.isNull(fileName)){
return null;
}
int index = fileName.lastIndexOf(DOT);
if(index == -1){
return EMPTY_STR;
}
return fileName.substring(index + 1,fileName.length());
}
/**
* @author: yc
* @des: InputStream 转 OutputStream
* @date: 2024/8/2 23:12
*/
public static void inputStream2outputStream(InputStream inputStream,OutputStream outputStream){
int count;
byte[] buff = new byte[4096];
try {
while((count = inputStream.read(buff)) != -1) {
if (count < -1) {
throw new RuntimeException("Can't have read < -1 bytes");
}
if (count > 0) {
outputStream.write(buff, 0, count);
}
}
}catch (Exception e){
System.out.println(e.getMessage());
}
}
/**
* @author: yc
* @des: 文件前缀模式枚举
* @date: 2024/06/07 16:24
*/
@Getter
@AllArgsConstructor
public enum FilePixModeEnum implements BaseEnum {
TIMESTAMP("TIMESTAMP","时间戳"),
UUID("UUID","随机字符串"),
NONE("NONE","无需前缀");
private String code;
private String name;
}
/**
* @author: yc
* @des: 获取当前时间戳
* @date: 2024/8/2 23:49
*/
public static long getTimestampNow(){
return System.currentTimeMillis();
}
/**
* @author: yc
* @des: 获取年月日 格式 yyyy/MM/dd
* @date: 2024/8/3 0:04
*/
public static String getYMD(String sdfStr){
//格式化时间
SimpleDateFormat sdf = new SimpleDateFormat(sdfStr);
String date = sdf.format(new Date());
return date;
}
}
使用示例
例如将内容为"hello word"的文本存入LOCAL_FILE_SAVE_PATH/dirName1/dirName2的文本中
public static void main(String[] args) {
System.out.println(FileUtils.str2file("hello world","hello",".txt","dirName1","dirName2", FilePixModeEnum.NONE,Boolean.FALSE));
}