import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import lombok.extern.slf4j.Slf4j;
/**
* 文件工具类
* @author LU HEIZE
*
*/
@Slf4j
public class FileUtil {
/**
*创建文件夹
* @param destDirName
* @return
*/
public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) {
System.out.println("创建目录" + destDirName + "失败,目标目录已经存在");
// return false;
return true;
}
//
// if (!destDirName.endsWith(File.separator)) {
// destDirName = destDirName + File.separator;
// }
//创建目录
if (dir.mkdirs()) {
System.out.println("创建目录" + destDirName + "成功!");
return true;
} else {
System.out.println("创建目录" + destDirName + "失败!");
return false;
}
}
/**
* zip解压
* @param filename 文件名
* @param destDirPath 解压后的目标文件夹
* @throws RuntimeException 解压失败会抛出运行时异常
*/
public static String unZip(String filename, String destDirPath) throws RuntimeException {
String excelName = "";
File srcFile = new File(filename);
long start = System.currentTimeMillis();
// System.out.println("文件大小"+srcFile.length());
// 判断源文件是否存在
if (!srcFile.exists()) {
throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
}
// 开始解压
ZipFile zipFile = null;
try {
zipFile = new ZipFile(srcFile,Charset.forName("GBK"));
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
// System.out.println("解压" + entry.getName());
String [] getName = entry.getName().split("\\.",2);
if(getName[1].equals("xlsx") || getName[1].equals("xls")) {
excelName = entry.getName();
}
// 如果是文件夹,就创建个文件夹
if (entry.isDirectory()) {
String dirPath = destDirPath + "/" + entry.getName();
File dir = new File(dirPath);
dir.mkdirs();
} else {
// 如果是文件,就先创建一个文件,然后用io流把内容copy过去
File targetFile = new File(destDirPath + "/" + entry.getName());
if(!getName[1].equals("xlsx") || !getName[1].equals("xls")) {
if(targetFile.length() > 204800) {
// return "Fail!!! 图片 ["+targetFile.getName() + "] 大小超过200KB , 上传失败!";
continue;
}
}
System.out.println("文件名"+targetFile.getName());
System.out.println("文件大小"+targetFile.length());
// 保证这个文件的父文件夹必须要存在
if(!targetFile.getParentFile().exists()){
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
// 将压缩文件内容写入到这个文件中
InputStream is = zipFile.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(targetFile);
int len;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
// 关流顺序,先打开的后关闭
fos.close();
is.close();
}
}
long end = System.currentTimeMillis();
System.out.println("解压完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("unzip error from ZipUtils", e);
} finally {
if(zipFile != null){
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return excelName;
}
/**
* 解压缩
* @param zippath 要解压的文件
* @param outzippath 解压路径
*/
public static void ZipContraMultiFile(String zippath ,String outzippath){
log.info("进入解压文件");
String msg = "";
try {
File file = new File(zippath);
File outFile = null;
ZipFile zipFile = new ZipFile(file);
ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));
ZipEntry entry = null;
InputStream input = null;
OutputStream output = null;
while((entry = zipInput.getNextEntry()) != null){
outFile = new File(outzippath + File.separator + entry.getName());
if(!outFile.getParentFile().exists()){
outFile.getParentFile().mkdir();
}
if(!outFile.exists()){
outFile.createNewFile();
}
input = zipFile.getInputStream(entry);
output = new FileOutputStream(outFile);
int temp = 0;
while((temp = input.read()) != -1){
output.write(temp);
}
input.close();
output.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 压缩单个文件
* @param filepath 文件名
* @param zippath 压缩后的文件名
* ZipFile("d:/hello.txt", "d:/hello.zip");
*/
public static void ZipFile(String filepath ,String zippath) {
try {
File file = new File(filepath);
File zipFile = new File(zippath);
InputStream input = new FileInputStream(file);
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
zipOut.putNextEntry(new ZipEntry(file.getName()));
int temp = 0;
while((temp = input.read()) != -1){
zipOut.write(temp);
}
input.close();
zipOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取文件
* @param request0 传入通道
* @return
*/
public static MultipartFile getHttpFile(HttpServletRequest request0) {
MultipartHttpServletRequest request = (MultipartHttpServletRequest) request0;
Map<String , MultipartFile> fileMap = request.getFileMap();
// String [] fileName = null ;
// int count = 0;
for (String key : fileMap.keySet()) {
// count ++;
System.out.println("fileName==>" + key);
MultipartFile file = fileMap.get(key);
// log.info( "file---->{}",file.getName() );
// fileName [count] = file.getName();
return file;
}
return null;
}
/**
* 下载文件
* @param request0
* @param path 本地路径
*/
public static Boolean saveHttpFile(HttpServletRequest request0 , String path ) {
log.info("进入保存文件");
MultipartFile httpFile = getHttpFile(request0);
// if (UtilsHelper.isEmpty(httpFile)) {
// return false;
// }
// String [] fileName = getHttpFile(request0);
// log.info("保存的fileName--->{}",fileName);
// MultipartFile httpFile = fileName;
try {
httpFile.transferTo(new File(path));
return true;
} catch (IllegalStateException e) {
// e.printStackTrace();
return false;
} catch (IOException e) {
return false;
// e.printStackTrace();
}
}
/**
* 处理云端路径 保存本地 获取本地路径
*/
public static String downUrl( String url_ ) {
String pictpath = "" ;//本地路径
try {
URL url = new URL(url_);
// 打开连接
URLConnection con = url.openConnection();
// 设置请求超时为5s
con.setConnectTimeout(5 * 1000);
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
//配置文件读取路径
String path = "";
// String path = "D://filepath//";
log.info("路径--->{}",path);
String fileName = url_.substring(url_.lastIndexOf("/")+1);;
log.info("截图的图片名--->{}",fileName);
// 输出的文件流
File f = new File(path);
if (!f.exists()) {
f.mkdirs();
}
// pictpath = path+"\\lala"+".jpg";
//截取云端路径的图片名
pictpath = path + fileName;
log.info("pictpath--->{}",pictpath);
OutputStream os = new FileOutputStream(pictpath);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return pictpath;
}
/**
* 切割文件
* 返回文件名List
* @param src 原大文件
* @param endsrc 切割后存放的小文件的路径
* @param num 切割规定的内存大小
* @return
*/
public static List<String> cutFile(String src, String endsrc, int num) {
List<String> nameList = new ArrayList<>();
FileInputStream fis = null;
File file = null;
try {
log.info("src=={}",src);
fis = new FileInputStream(src);
file = new File(src);
//创建规定大小的byte数组
byte[] b = new byte[num];
int len = 0;
//name为以后的小文件命名做准备
int name = 1;
//遍历将大文件读入byte数组中,当byte数组读满后写入对应的小文件中
while ((len = fis.read(b)) != -1) {
//分别找到原大文件的文件名和文件类型,为下面的小文件命名做准备
String name2 = file.getName();
int lastIndexOf = name2.lastIndexOf(".");
String substring = name2.substring(0, lastIndexOf);
String substring2 = name2.substring(lastIndexOf, name2.length());
String spliceFileName = endsrc + substring + "-" + name + substring2;
log.info("spliceFileName=={}",spliceFileName);
FileOutputStream fos = new FileOutputStream(spliceFileName);
//将byte数组写入对应的小文件中
fos.write(b, 0, len);
//结束资源
fos.close();
name++;
nameList.add(spliceFileName);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
//结束资源
fis.close();
}
return nameList;
} catch (IOException e) {
e.printStackTrace();
}
}
return nameList;
}
public static void main(String[] args) {
ZipFile("D:/filepath/zzzz.png","D:/filepath/mm.zip");
// downUrl("http://ylfpicture.one-cm3.com/agriculturalMobile/xh.png");
// //调用cutFile()函数 传人参数分别为 (原大文件,切割后存放的小文件的路径,切割规定的内存大小)
// List<String> nameList = cutFile("D:/filepath/超清mz.jpg", "D:/filepath/",2097152);
//
// try {
// Thread.sleep(5000);
//
// for (String string : nameList) {
// File file = new File(string);
// if(file.exists()) {
// file.delete();
// System.out.println("删除成功");
// }
// }
// } catch (InterruptedException e) {
// // TODO 自动生成的 catch 块
// e.printStackTrace();
// }
}
}
FileUtil
于 2023-05-13 18:02:09 首次发布
该Java类提供了文件操作功能,如创建目录、解压缩ZIP文件到指定目录,同时检查解压后的文件大小。它还包含压缩文件方法及从HTTP请求中获取MultipartFile的功能。
摘要由CSDN通过智能技术生成