工具类。可以直接复制粘贴。一些路径的Global需要自己写
import com.manage.common.core.web.domain.ImgUrlEntity;
import com.manage.common.global.filepath.FileGlobal;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;
public class FileUtil {
/**
* 下载文件
*
* @param realPath 初始路径
* @param fileName 文件名
*/
public static void downloadFile(String realPath, String fileName, HttpServletResponse response) {
ServletOutputStream out = null;
FileInputStream inputStream = null;
try {
inputStream = FileUtils.openInputStream(new File(realPath + fileName));
// 防止下载时名称乱码
response.setContentType("multipart/form-data");
fileName = new String(fileName.getBytes("gbk"), "iso8859-1");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
out = response.getOutputStream();
int b = 0;
byte[] buffer = new byte[512];
while (b != -1) {
b = inputStream.read(buffer);
if (b != -1) {
out.write(buffer, 0, b);//4.写到输出流(out)中
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (out != null) {
out.close();
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 保存上传的图片
*
* @param realPath 初始路径
* @param file 文件信息对象
* @return 返回保存后的文件名
* @throws IOException
*/
public static String savePhotoFile(String realPath, MultipartFile file) throws IOException {
//获取文件的后缀
String prefix = getFilePrefix(file);
//获取备份名称
String fileName = getBakFileName(file);
fileName = fileName.split("\\.")[0] + ".jpg";
//保存文件
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, fileName));
//不是图片格式则删除
String[] photoFormat = {"jpg", "jpeg", "JPG", "png", "PNG"};
if (!Arrays.asList(photoFormat).contains(prefix)) {
//删除文件
FileUtils.deleteQuietly(new File(realPath + fileName));
}
return fileName;
}
/**
* 将临时目录中的文件保存到真实路径中
*
* @param temporaryPath 临时路径加文件名
* @return 返回保存后的文件名
* @throws IOException
*/
public static String saveRealPhotoFile(String temporaryPath) {
//获取临时路径下的文件对象
File temporaryFile = new File(temporaryPath);
//获取真实路径,和文件名
String separator = "\\\\";
if ("Linux".equals(System.getProperty("os.name"))) {//判断当前系统
separator = File.separator;
}
String[] strs = temporaryPath.split(separator);
// String[] strs = temporaryPath.split("\\\\");
String realPath = "";
String fileName = "";
for (int i = 0; i < strs.length; i++) {
if (i == strs.length - 1) {
fileName = strs[i];
break;
}
if (i == strs.length - 2) {
temporaryPath = realPath + strs[i] + File.separator;
continue;
}
realPath += strs[i] + File.separator;
}
try {
//保存文件
FileUtils.copyInputStreamToFile(new FileInputStream(FileGlobal.FILE_BASE_PATH + temporaryFile.getPath()), new File(FileGlobal.FILE_BASE_PATH + realPath + fileName));
//删除临时目录
FileUtils.deleteDirectory(new File(FileGlobal.FILE_BASE_PATH + temporaryPath));
} catch (IOException e) {
e.printStackTrace();
}
return realPath + fileName;
}
/**
* 保存上传的文件,修改文件名为时间戳
*
* @param realPath 初始路径
* @param file 文件信息对象
* @return 文件名称
* @throws IOException
*/
public static String savePackageFile(String realPath, MultipartFile file) throws IOException {
//获取文件名
String fileName = new Date().getTime() + "." + getFilePrefix(file);
//保存文件
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, fileName));
return fileName;
}
/**
* 保存上传的文件,修改文件名为时间戳
*
* @param realPath 初始路径
* @param file 文件信息对象
* @return 文件名称
* @throws IOException
*/
public static String savePackageFileRealName(String realPath, MultipartFile file) throws IOException {
//获取文件名
String fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) + new Date().getTime() + "." + getFilePrefix(file);
//保存文件
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, fileName));
return fileName;
}
/**
* 保存上传的文件,文件名不修改
*
* @param realPath 初始路径
* @param file 文件信息对象
* @return 文件名称
* @throws IOException
*/
public static String saveFile(String realPath, MultipartFile file) throws IOException {
//获取文件名
String fileName = file.getOriginalFilename();
//保存文件
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, fileName));
return fileName;
}
/**
* 删除文件
*
* @param path 路径
* @return
* @throws IOException
*/
public static boolean delFileByPath(String path) throws IOException {
//删除文件
return FileUtils.deleteQuietly(new File(FileGlobal.FILE_BASE_PATH + path));
}
/**
* 保存图片
*
* @param type 1=截图
* @param bytes
* @param fileTypeSuffix
* @return
*/
public static ImgUrlEntity uploadPic(int type, byte[] bytes, String fileTypeSuffix) {
String path = "";
String url = "";
switch (type) {
case 1:
String timeStr = TimeUtil.getDateTimeArray()[0] + "/" + TimeUtil.getDateTimeArray()[1] + "/" + TimeUtil.getDateTimeArray()[2] + "/";
path = FileGlobal.FILE_BASE_PATH + FileGlobal.ALARM_SCREENSHOT + timeStr;
url = FileGlobal.ALARM_SCREENSHOT + timeStr;
break;
case 2:
String timeStr2 = TimeUtil.getDateTimeArray()[0] + "/" + TimeUtil.getDateTimeArray()[1] + "/" + TimeUtil.getDateTimeArray()[2] + "/";
path = FileGlobal.FILE_BASE_PATH + FileGlobal.DATA_COLLEC_INFO + timeStr2;
url = FileGlobal.DATA_COLLEC_INFO + timeStr2;
break;
}
String name = UUID.randomUUID().toString();
String originalFileName = name + "_original." + fileTypeSuffix;
String thumbnailFileName = name + "_thumbnail." + fileTypeSuffix;
int fileType = 0;
String fileSuffix = fileTypeSuffix.toLowerCase();
if (fileSuffix.endsWith("mp4") || fileSuffix.endsWith("avi")
|| fileSuffix.endsWith("3gpp") || fileSuffix.endsWith("3gp") || fileSuffix.startsWith("mov"))
fileType = 1;
try {
File file = new File(path + "/" + originalFileName);
FileUtils.writeByteArrayToFile(file, bytes);
} catch (Exception e) {
e.printStackTrace();
return new ImgUrlEntity();
}
try {
if (fileType == 0)
ImageHelper.zoomImage(path + "/" + originalFileName, path + "/" + thumbnailFileName, 120, 120);
} catch (Exception e) {
e.printStackTrace();
return new ImgUrlEntity();
}
return new ImgUrlEntity(url + originalFileName, url + thumbnailFileName, fileType);
}
public static File file_put_contents(String savePath, InputStream is) {
File file = new File(savePath);
OutputStream os = null;
try {
os = new FileOutputStream(file);
byte buffer[] = new byte[4 * 1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
/**
* 保存上传的excel
*
* @param realPath 初始路径
* @param file 文件信息对象
* @throws IOException
*/
public static String saveExcelFile(String realPath, MultipartFile file) throws IOException {
//获取文件的后缀
String prefix = getFilePrefix(file);
//获取备份名称
String fileName = getBakFileName(file);
//保存文件
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, fileName));
//不是图片格式则删除
String[] formatArr = {"xlsx", "xls"};
if (!Arrays.asList(formatArr).contains(prefix)) {
//删除文件
FileUtils.deleteQuietly(new File(realPath + fileName));
}
return fileName;
}
/**
* 获取文件的后缀
*
* @param file
* @return
*/
public static String getFilePrefix(MultipartFile file) {
//获取文件名称
String originalFilename = file.getOriginalFilename();
//获取文件的后缀
return originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
}
/**
* 生成文件的备份名称
*
* @param file
* @return
*/
public static String getBakFileName(MultipartFile file) {
//获取文件名称
// String originalFilename = file.getOriginalFilename();
//获取当前时间的毫秒级
Date date = new Date();
long time = date.getTime();
//获取文件的后缀
String prefix = getFilePrefix(file);
//修改为备份文件名
return String.valueOf(time) + "-" + Utils.genUUID().substring(0, 5) + "." + prefix;
}
// 计算文件的 MD5 值 根据MD5值 判断文件是否是同一个文件
public static String getFileMD5(File file) {
if (!file.isFile()) {
return null;
}
MessageDigest digest = null;
FileInputStream in = null;
byte buffer[] = new byte[8192];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer)) != -1) {
digest.update(buffer, 0, len);
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 创建文件并写入内容
*
* @param content
* @param path
* @throws IOException
*/
public static void writeFile(String content, String path) throws IOException {
File file = new File(path);
FileUtils.write(file, content + "\r\n", "utf-8", true);
}
}
简单应用
//文件路径 FileGlobal.FILE_BASE_PATH 基础路径,例如:D:\sougou
// FileGlobal.DATA_TEST_URL 文件具体路径
String realPath = FileGlobal.FILE_BASE_PATH + FileGlobal.DATA_TEST_URL;
String url = FileGlobal.DATA_TEST_URL+ FileUtil.savePhotoFile(realPath, file);