1.maven
<!-- 解压rar -->
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>0.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.1.2</version>
</dependency>
2. 工具类
package com.dlax.pinfo.common.utils;
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
/**
* @author l
* @version 1.0
* @PACKAGE_NAME: com.dlax.pinfo.common.utils
* @date 2022/3/31 16:27 周四
* 解压上传zip文件
*/
@Slf4j
public class ZipUtils {
public ZipUtils() {
}
/**
* @param sourcefiles 源文件(服务器上的zip包存放地址)
* @param decompreDirectory 解压缩后文件存放的目录
* @throws IOException IO异常
* <p>
* 例子 unzip(new File("E:/Study/java.zip"), "E:/Study/unzip/");
*/
@SuppressWarnings("unchecked")
public static void unzip(String sourcefiles, String decompreDirectory) throws IOException {
ZipFile readfile = null;
try {
readfile = new ZipFile(sourcefiles, Charset.forName("GBK"));
//,枚举
Enumeration takeentrie = readfile.entries();
ZipEntry zipEntry = null;
File credirectory = new File(decompreDirectory);
credirectory.mkdirs();
while (takeentrie.hasMoreElements()) {
zipEntry = (ZipEntry) takeentrie.nextElement();
String entryName = zipEntry.getName();
InputStream in = null;
FileOutputStream out = null;
try {
if (zipEntry.isDirectory()) {
String name = zipEntry.getName();
name = name.substring(0, name.length() - 1);
File createDirectory = new File(decompreDirectory + File.separator + name);
createDirectory.mkdirs();
} else {
int index = entryName.lastIndexOf("\\");
if (index != -1) {
File createDirectory = new File(decompreDirectory + File.separator + entryName.substring(0, index));
createDirectory.mkdirs();
}
index = entryName.lastIndexOf("/");
if (index != -1) {
File createDirectory = new File(decompreDirectory + File.separator + entryName.substring(0, index));
createDirectory.mkdirs();
}
File unpackfile = new File(decompreDirectory + File.separator + zipEntry.getName());
in = readfile.getInputStream(zipEntry);
out = new FileOutputStream(unpackfile);
int c;
byte[] by = new byte[1024];
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
out.flush();
}
} catch (IOException ex) {
ex.printStackTrace();
throw new IOException("解压失败:" + ex.toString());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
in = null;
out = null;
}
}
} catch (IOException ex) {
throw new IOException("解压失败:" + ex.toString());
} finally {
if (readfile != null) {
try {
readfile.close();
} catch (IOException ex) {
throw new IOException("解压失败:" + ex.toString());
}
}
}
}
/**
* 解压rar格式压缩包。
* 对应的是java-unrar-0.3.jar,但是java-unrar-0.3.jar又会用到commons-logging-1.1.1.jar
*/
@SuppressWarnings("unchecked")
public static void unrar(String sourceRar, String destDir) throws Exception {
Archive a = null;
FileOutputStream fos = null;
try {
a = new Archive(new File(sourceRar));
FileHeader fh = a.nextFileHeader();
while (fh != null) {
if (!fh.isDirectory()) {
//1 根据不同的操作系统拿到相应的 destDirName 和 destFileName
//String compressFileName = fh.getFileNameString().trim();
String compressFileName = fh.getFileNameW().trim();
if (!existZH(compressFileName)) {
compressFileName = fh.getFileNameString().trim();
}
String destFileName = "";
String destDirName = "";
//非windows系统
if (File.separator.equals("/")) {
destFileName = destDir + compressFileName.replaceAll("\\\\", "/");
destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));
//windows系统
} else {
destFileName = destDir + compressFileName.replaceAll("/", "\\\\");
destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));
}
//2创建文件夹
File dir = new File(destDirName);
if (!dir.exists() || !dir.isDirectory()) {
dir.mkdirs();
}
//3解压缩文件
fos = new FileOutputStream(new File(destFileName));
a.extractFile(fh, fos);
fos.close();
fos = null;
}
fh = a.nextFileHeader();
}
a.close();
a = null;
} catch (Exception e) {
log.error("解压rar格式压缩包失败:"+ e.getMessage());
} finally {
if (fos != null) {
try {
fos.close();
fos = null;
} catch (Exception e) {
log.error("fos.close失败:"+ e.getMessage());
}
}
if (a != null) {
try {
a.close();
a = null;
} catch (Exception e) {
log.error("a.close失败:"+ e.getMessage());
}
}
}
}
/**
* 获得以.xls为后缀的Excel文件
*
* @param path
* @return
*/
public static File getExcelFile(String path) {
File file = new File(path);
//判断当前目录是否存在
if (!file.exists()) {
log.error("获得以.xls为后缀的Excel文件失败!");
return null;
}
//取得当前目录下所有文件和文件夹
String[] content = file.list();
for (String name : content) {
File temp = new File(path, name);
//判断是否是目录
if (temp.isDirectory()) {
String[] con = temp.list();
for (String name1 : con) {
if (name1.endsWith(".xls") || name1.endsWith(".xlsx")) {
File excelFile = new File(temp, name1);
return excelFile;
}
}
} else if (name.endsWith(".xls") || name.endsWith(".xlsx")) {
return temp;
}
}
return null;
}
/**
* 解决linux下rar包名字中文乱码
*
* @param str
* @return
*/
public static boolean existZH(String str) {
String regEx = "[\\u4e00-\\u9fa5]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
while (m.find()) {
return true;
}
return false;
}
/**
* 获取zip包下的文件夹名称
*
* @param path
* @return
* @throws IOException
*/
public static String readZipFile(String path) {
String mFileChange = null;
ZipEntry zipEntry = null;
ZipInputStream zipInputStream = null;
File file = new File(path);
try {
//判断文件是否存在
if (file.exists()) {
//解决包内文件存在中文时的中文乱码问题
FileInputStream fileInputStream = new FileInputStream(path);
zipInputStream = new ZipInputStream(fileInputStream, Charset.forName("GBK"));
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
//只读取包内根目录文件的文件名
if (zipEntry.isDirectory()) {
mFileChange = zipEntry.getName();
}
// else {
// mFileChange += zipEntry.getName().substring(zipEntry.getName().lastIndexOf("/") + 1, zipEntry.getName().lastIndexOf(".")) + "\n";
// }
}
}
log.info("拼接后的文件名称为:" + mFileChange);
} catch (Exception e) {
log.error("获取zip包下的文件夹名称失败:"+ e.getMessage());
} finally {
if (zipInputStream != null) {
try {
zipInputStream.close();
} catch (IOException e) {
log.error("关闭zip包下的文件夹名称失败:" + e.getMessage());
}
}
}
return mFileChange;
}
/**
* 删除生成的zip包
* @param f
* @param name
*/
public static void delete(File f, String name) {
//数组指向文件夹中的文件和文件夹
File[] fi = f.listFiles();
//遍历文件和文件夹
for (File file : fi) {
if (file.isFile()) {
//是文件的话,把文件名放到一个字符串中
String filename = file.getName();
if (filename.equals(name)) {
file.delete();
}
}
}
}
/**
* 删除文件夹
* @param file
*/
public static void deleteFile(File file) {
//判断文件不为null或文件目录存在
if (file == null || !file.exists()) {
log.info("文件删除失败,请检查文件路径是否正确");
}
//取得这个目录下的所有子文件对象
File[] files = file.listFiles();
//遍历该目录下的文件对象
for (File f : files) {
//判断子目录是否存在子目录,如果是文件则删除
if (f.isDirectory()) {
deleteFile(f);
} else {
f.delete();
}
}
//删除空文件夹 for循环已经把上一层节点的目录清空。
file.delete();
}
}
3.POIutils?工具类
package com.dlax.pinfo.common.utils;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import lombok.extern.slf4j.Slf4j;
import java.io.InputStream;
import java.util.List;
/**
* @author l
* @version 1.0
* @PACKAGE_NAME: com.dlax.pinfo.common.utils
* @date 2022/3/31 16:38 周四
*/
@Slf4j
public class POIutils {
/**
* poi获取表格数据
*
* @param input
* @param pojoClass
* @param <T>
* @return
*/
public static <T> List<T> importExcel(InputStream input, Class<T> pojoClass) {
if (input == null) {
return null;
}
ImportParams params = new ImportParams();
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(input, pojoClass, params);
} catch (Exception e) {
list.add((T) "");
log.error("poi获取表格数据失败:" + e.getMessage());
}
return list;
}
}
?4.引用类
@RequestMapping(value = "/importZip", method = RequestMethod.POST)
public synchronized CommonResult importStaffZip(MultipartFile file) {
CommonResult commonResult=null;
if (file == null || file.isEmpty()) {
return CommonResult.failed("请选择导入文件");
}
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
if (!".zip".equals(suffix) && !".rar".equals(suffix)) {
return CommonResult.failed("导入文件格式错误");
}
// // 判断是否可以导入 系统中同一时间只能有一处导入
// if (excelProgressUtils.canImport()) {
// return CommonResult.ok(null, "导入功能正在使用,请稍后再试!", -1);
// }
// 保存文件到指定目录
String filePath = dPath + file.getOriginalFilename();
//解压后的文件路径
String fileUrl = null;
InputStream inputStream =null;
try {
// 保存文件
File dest = new File(filePath);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
if (!file.isEmpty()) {
//转存文件到服务器
file.transferTo(dest);
}
//保证文件夹路径最后是"/"或者"\"
char lastChar = dPath.charAt(dPath.length() - 1);
if (lastChar != '/' && lastChar != '\\') {
dPath += File.separator;
}
// 压缩包里面的文件名
String getfileName= ZipUtils.readZipFile(filePath);
//根据类型,进行相应的解压缩
String type = filePath.substring(filePath.lastIndexOf(".") + 1);
if (type.equals("zip")) {
ZipUtils.unzip(filePath, dPath);
} else if (type.equals("rar")) {
ZipUtils.unrar(filePath, dPath);
}
if(StringUtils.isBlank(getfileName)){
return CommonResult.failed("获取压缩包里面的文件名失败");
}
//解压后的文件路径
fileUrl = dPath + getfileName.split("/")[0];
//判断导入的包是否为空
File excelFile = ZipUtils.getExcelFile(dPath);
if (excelFile== null) {
// 删除压缩包以及文件夹
File file1 = new File(dPath);
//删除文件
ZipUtils.delete(file1, file.getOriginalFilename());
//删除文件夹
ZipUtils.deleteFile(file1);
return CommonResult.failed("导入文件格式错误");
}
//读取Excel文件获取值
Class<ExcelPersonTable> entity = ExcelPersonTable.class;
File newFile = ZipUtils.getExcelFile(fileUrl);
inputStream = new FileInputStream(newFile);
List<ExcelPersonTable> excelPersonDataList = POIutils.importExcel(inputStream, entity);
if (excelPersonDataList == null) {
//删除文件
File file1 = new File(dPath);
ZipUtils.delete(file1, file.getOriginalFilename());
ZipUtils.deleteFile(file1);
return CommonResult.failed("人员信息为空");
}
log.info("获取excel表格的数据:"+JSONUtil.toJsonStr(excelPersonDataList));
commonResult=basaePersonService.addExcelPersonData(fileUrl,excelPersonDataList);
} catch (Exception e) {
log.error("导入人员失败:" + e.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
log.error("inputStream.close失败:"+ e.getMessage());
}
}
// 删除压缩包以及文件夹
File file1 = new File(dPath);
ZipUtils.delete(file1, file.getOriginalFilename());
File file2 = new File(fileUrl);
ZipUtils.deleteFile(file2);
}
return commonResult;
}
|