import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 文件工具类
*/
public class FileUtils{
private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);
/**
* 删除文件
* @param file true成功false失败
*/
public static boolean deleteFile(File file) {
boolean flag = false;
try {
if (file.isFile()) {
flag = file.delete();
}
} catch (Exception e) {
flag = false;
}
return flag;
}
/**
* 删除文件
* @param fileName 为空直接返回false,不做其他处理 true成功false失败
*/
public static boolean deleteFile(String fileName) {
if(StringUtils.isBlank(fileName)){
return false;
}else{
return deleteFile(new File(fileName));
}
}
/**
* 上传资源
* @param file MultipartFile文件
* @param path 相对路径
* @param sourceFileName 原文件名称
*/
public static Map<String,String> MultipartFileUpload(MultipartFile file, String path, String sourceFileName){
Map<String,String> map = new HashMap<>();
InputStream is = null;
FileOutputStream fos = null;
File newFile = null;
try{
File tpath = new File(DynamicUtils.RESOURCE_BASE_PATH + path);
//创建文件夹
if (!tpath.exists()) {
tpath.mkdirs();
}
String fileName = UUIDUtils.create32UUID() + "." + getSuffix(sourceFileName);
newFile = new File(DynamicUtils.RESOURCE_BASE_PATH + path + fileName);
is = file.getInputStream();
fos = new FileOutputStream(newFile);
byte[] bu = new byte[1024];
int len;
while ((len = is.read(bu)) > 0) {
fos.write(bu, 0, len);
}
fos.close();
is.close();
//获取资源信息
map.put("length", PubUtils.toStr(newFile.length()));
map.put("md5", getMd5(newFile));
map.put("oldFileName", sourceFileName);
map.put("fileName", fileName);
map.put("path", path + fileName);
map.put("suffix", getSuffix(fileName));
} catch (Exception e) {
logger.info("上传文件失败", e);
} finally {
if (fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.gc();
}
return map;
}
/**
* 拷贝文件
* @param srcFileStr
* @param descFileStr
*/
public static void copyFile(String srcFileStr, String descFileStr){
try {
File srcFile = new File(srcFileStr);
File descFile = new File(descFileStr);
org.apache.commons.io.FileUtils.copyFile(srcFile, descFile);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取文件MD5
* @param file
*/
public static String getMd5(File file){
String rtn = "";
try {
rtn = DigestUtils.md5Hex(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return rtn;
}
/**
* 获取路径扩展名
* @param path
*/
public static String getSuffix(String path){
if(StringUtils.isNotBlank(path) && StringUtils.contains(path, ".")){
return path.substring(path.lastIndexOf(".") + 1, path.length());
}else{
return "";
}
}
/**
* 计算基本资源路径
* @param app 应用代码
* @param business 业务代码
* @param sourceType 资源类型
*/
public static String getFilePath(String app, String business, String sourceType){
return ConstantUtils.RESOURCE_PATH_TPL
.replace("{app}", "")
.replace("{business}", PubUtils.toStr(business, "dft"))
.replace("{resource-type}", sourceType)
.replace("{date}", "")
.replace("//", "/");
}
/**
* 获取指定文件夹下所有文件路径
*
* @param path java.util.List<java.io.File>
*/
public static List<File> getFiles(String path) throws Exception {
//目标集合fileList
List<File> fileList = new ArrayList<>();
File file = new File(path);
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File fileIndex : files) {
//如果这个文件是目录,则进行递归搜索
if (fileIndex.isDirectory()) {
getFiles(fileIndex.getPath());
} else {
//如果文件是普通文件,则将文件句柄放入集合中
fileList.add(fileIndex);
}
}
}
return fileList;
}
/**
* 下载项目根目录下doc下的文件
* @param response response
* @param filePath 文件名 返回结果 成功或者文件不存在
*/
public static void downloadFile(HttpServletResponse response, String filePath) {
File file = new File(filePath);
if(!file.exists()){
return ;
}
String fileName = file.getName();
File path = null;
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
try {
response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
}
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = response.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
response.setHeader("Content-Length", String.valueOf(bis.available()));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
FileUtils
最新推荐文章于 2022-01-11 13:59:07 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)