最近开发任务比较多,这两天陆陆续续整理了一点资料上传一下,这个是前段时间用到的解压和压缩文件的工具类,网上找了一些,自己补充一下,现在先分享一下,希望对各位同学有所帮助!

package com.aspirecn.audit.engneer.common.util;import net.lingala.zip4j.model.FileHeader;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;/***  TODO*  *  @author wangyanhui*  @date 2018-07-09 13:52*  */
public class FileUtil {private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);private static String[] SUFFIX_NAMES = {".zip", ".rar", ".7z"};private static String ZIP = ".zip";private static String RAR = ".rar";private static String SEVEN_Z = ".7z";/*** 使用MD5编码成32位字符串** @param inputStr* @return String*/public static String encodeInMD5(final String inputStr) {if (StringUtils.isEmpty(inputStr)) {return inputStr;}return DigestUtils.md5DigestAsHex(inputStr.getBytes());}/*** 生成存放文件路径** @return path*/public static String generateRelativeDir() {// 当前日期final Date date = new Date();// 格式化并转换String类型final String path = new SimpleDateFormat("yyyy/MM/dd").format(date);return path;}/*** 生成FileId   例如:201806181701001+7位随机数** @return fileId*/public static String createFileId() {StringBuffer path = new StringBuffer();Date date = new Date();DateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");String time = format.format(date);path.append(time);Random random = new Random();int numCount = 7;for (int i = 0; i < numCount; i++) {path.append(String.valueOf(random.nextInt(10)));}return path.toString();}/*** 删除指定文件** @param path*/public static void deleteFile(final String path) {final File file = new File(path);if (file.exists() && file.isFile()) {file.delete();}}/*** 删除文件夹及其下的所有子文件夹和文件** @param folderPath*/public static void deleteFolder(String folderPath) {try {File baseFolder = new File(folderPath);if (baseFolder.exists()) {deleteAllFileInFolder(folderPath);baseFolder.delete();}} catch (Exception e) {logger.error(e.getMessage(), e);}}public static boolean deleteAllFileInFolder(String path) {boolean flag = false;File file = new File(path);if (!file.exists()) {return flag;}if (!file.isDirectory()) {return flag;}String[] tempList = file.list();File temp = null;for (int i = 0; i < tempList.length; i++) {if (path.endsWith(File.separator)) {temp = new File(path + tempList[i]);} else {temp = new File(path + File.separator + tempList[i]);}if (temp.isFile()) {temp.delete();}if (temp.isDirectory()) {deleteAllFileInFolder(path + File.separator + tempList[i]);deleteFolder(path + File.separator + tempList[i]);flag = true;}}return flag;}/*** 移动文件(强制覆盖)** @param srcFileName      源文件完整路径* @param destDirName      目的目录完整路径* @param originalFileName 保存的文件名称* @return 文件移动成功返回true,否则返回false*/public static boolean moveFile(final String srcFileName, final String destDirName, String originalFileName) {//源文件final File srcFile = new File(srcFileName);if (!srcFile.exists() || !srcFile.isFile()) {return false;}//目标文件夹final File destDir = new File(destDirName);if (!destDir.exists()) {destDir.mkdirs();}// 固定文件存放路径return srcFile.renameTo(new File(destDirName + File.separator + originalFileName));}/*** 移动文件(强制覆盖)** @param srcFileName      源文件完整路径* @param destDirName      目的目录完整路径* @param originalFileName 保存的文件名称* @return 文件移动成功返回true,否则返回false*/public static boolean moveFileForce(final String srcFileName, final String destDirName, String originalFileName) {//源文件final File srcFile = new File(srcFileName);if (!srcFile.exists() || !srcFile.isFile()) {return false;}//目标文件夹final File destDir = new File(destDirName);if (!destDir.exists()) {destDir.mkdirs();}//目标文件File desFile = new File(destDirName + File.separator + originalFileName);//目标文件存在,且不与源文件在同一目录,删除目标文件if (desFile.exists() && !srcFile.getPath().equals(desFile.getPath())) {desFile.delete();}// 固定文件存放路径return srcFile.renameTo(desFile);}/*** 复制文件** @param srcFileName* @param destDirName* @param originalFileName*/public static void copyFile(final String srcFileName, String destDirName, String originalFileName) {final File destDir = new File(destDirName);if (!destDir.exists()) {destDir.mkdirs();}FileChannel inputChannel = null;FileChannel outputChannel = null;try {inputChannel = new FileInputStream(srcFileName).getChannel();outputChannel = new FileOutputStream(destDirName + File.separator + originalFileName).getChannel();outputChannel.transferFrom(inputChannel, 0, inputChannel.size());} catch (IOException e) {logger.error(e.getMessage(), e);} finally {try {inputChannel.close();outputChannel.close();} catch (IOException e) {logger.error(e.getMessage(), e);}}}/*** 从http Url中下载文件** @param urlStr* @param fileName* @param savePath* @throws IOException*/public static boolean downLoadFromUrl(String urlStr, String fileName, String savePath) {URL url = null;HttpURLConnection conn = null;FileOutputStream fos = null;InputStream is = null;try {url = new URL(urlStr);conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(30 * 1000);is = conn.getInputStream();byte[] getData;byte[] buffer = new byte[1024];int len = 0;ByteArrayOutputStream bos = new ByteArrayOutputStream();while ((len = is.read(buffer)) != -1) {bos.write(buffer, 0, len);}getData = bos.toByteArray();bos.close();File saveDir = new File(savePath);if (!saveDir.exists()) {saveDir.mkdir();}File file = new File(saveDir + File.separator + fileName);fos = new FileOutputStream(file);fos.write(getData);return true;} catch (MalformedURLException e) {logger.error(e.getMessage(), e);} catch (IOException e) {logger.error(e.getMessage(), e);} finally {if (fos != null) {try {fos.close();} catch (IOException e) {logger.error(e.getMessage(), e);}}if (is != null) {try {is.close();} catch (IOException e) {logger.error(e.getMessage(), e);}}}return false;}/*** 解压缩zip包** @param zipFilePath zip文件的全路径* @param targetPath  解压后的文件保存的路径* @param targetPath  解压后的文件保存的路径* @return*/public static String unzip(String zipFilePath, String targetPath, boolean isInSameDir) {StringBuffer msg = new StringBuffer();OutputStream os = null;InputStream is = null;ZipFile zipFile = null;try {zipFile = new ZipFile(zipFilePath, Charset.forName("GBK"));File directoryFile = new File(targetPath);if (!directoryFile.exists()) {directoryFile.mkdir();}Enumeration<?> entryEnum = zipFile.entries();if (null != entryEnum) {ZipEntry zipEntry = null;int len = 4096;String zipFileName = "";while (entryEnum.hasMoreElements()) {zipEntry = (ZipEntry) entryEnum.nextElement();if (zipEntry.getSize() > 0) {zipFileName = zipEntry.getName();// 处理解压文件保存到同一目录if (isInSameDir) {if (zipFileName.indexOf(File.separator) > -1) {zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1, zipFileName.length());if (zipFileName.startsWith("~$")) {continue;}}}//判断文件是否已经存在。if (checkFileExistence(targetPath, zipFileName)) {//msg.setLength(0);msg.append("存在重复的文件名:" + zipFileName);}// 文件File targetFile = new File(targetPath + File.separator + zipFileName);os = new BufferedOutputStream(new FileOutputStream(targetFile));is = zipFile.getInputStream(zipEntry);byte[] buffer = new byte[4096];int readLen = 0;while ((readLen = is.read(buffer, 0, len)) >= 0) {os.write(buffer, 0, readLen);os.flush();}
//                        if (zipFileName.lastIndexOf(".") > -1) {
//                            String suffix = zipFileName.substring(zipFileName.lastIndexOf("."), zipFileName.length()).toLowerCase();
//                            if (zipFileName.lastIndexOf(".") > -1 && Arrays.asList(SUFFIX_NAMES).contains(suffix)) {
//                                String ret = unCompressedFilesToSameDir(targetPath + File.separator + zipFileName, targetPath, suffix);
//                                if (!StringUtil.isEmpty(ret)) {
//                                    //msg.setLength(0);
//                                    msg.append(ret);
//                                }
//                            }
//                        }}if (zipEntry.isDirectory()) {File file = new File(targetPath + File.separator + zipEntry.getName());if (!file.exists()) {file.mkdir();}}if (null != is) {is.close();}if (null != os) {os.close();}}}closeZipStream(zipFile, is, os);//如果解压的文件在在目标文件夹中,将其删除if (zipFilePath.contains(targetPath)) {new File(zipFilePath).delete();}if (isInSameDir) {String ret = moveToRootDir(targetPath);if (!StringUtils.isEmpty(ret)) {msg.append(ret);}}if (null != directoryFile) {StringBuffer stringBuffer = unFile(directoryFile, targetPath, isInSameDir);msg.append(stringBuffer);}return msg.toString();} catch (IOException e) {logger.error(e.getMessage(), e);} finally {closeZipStream(zipFile, is, os);}return msg.toString();}public static StringBuffer unFile(File sourceFile, String targetPath, boolean isInSameDir) {StringBuffer msg = new StringBuffer();File[] sourceFiles = sourceFile.listFiles();for (File sf : sourceFiles) {if (sf.isFile() && sf.length() > 0) {String filePath = sf.getPath();if (filePath.lastIndexOf(".") > -1) {//获取文件的后缀String suffix = filePath.substring(filePath.lastIndexOf("."), filePath.length()).toLowerCase();//如果是压缩包,继续解压缩,也就是解压到目标目录下没有rar文件位置if (filePath.lastIndexOf(".") > -1 && Arrays.asList(SUFFIX_NAMES).contains(suffix)) {String ret = unCompressedFilesToSameDir(filePath, targetPath, suffix);if (!StringUtils.isEmpty(ret)) {msg.append(ret);}}}}if (sf.isDirectory()) {if (isInSameDir) {unFile(sf, targetPath, isInSameDir);} else {unFile(sf, sf.getAbsolutePath(), isInSameDir);}}}return msg;}/*** 判断解压的文件在解压目录下是否存在** @param targetPath* @param zipFileName* @return*/private static boolean checkFileExistence(String targetPath, String zipFileName) {boolean exist = false;File target = new File(targetPath);if (target.isDirectory()) {File[] files = target.listFiles();for (File file : files) {if (!file.isDirectory()) {String fileName = file.getName();if (fileName.equals(zipFileName)) {exist = true;break;}}}}return exist;}/*** 关闭zip流** @param zipFile* @param is* @param os*/private static void closeZipStream(ZipFile zipFile, InputStream is, OutputStream os) {if (null != zipFile) {try {zipFile.close();} catch (IOException e) {logger.error(e.getMessage(), e);}}if (null != is) {try {is.close();} catch (IOException e) {logger.error(e.getMessage(), e);}}if (null != os) {try {os.close();} catch (IOException e) {logger.error(e.getMessage(), e);}}}public static String un7z(String rarFilePath, String targetPath) {//String filePath = null;String cmd = null;if (OSinfo.isWindows()) {/*filePath = targetPath + "\\" + UUID.randomUUID().toString().replace("-","") + ".7z";rarFilePath = rarFilePath.substring(0, rarFilePath.length() - 1) + "*";cmd = "cmd.exe /c copy /b " + rarFilePath + " " + filePath;*///合并cmd = "7z x -r " + rarFilePath + " -o" + targetPath;} else if (OSinfo.isLinux()) {cmd = "7z x -r " + rarFilePath + " -o" + targetPath;}ShellUtil.excuete(cmd);return targetPath;}private static final ArrayList<String> suffixList = new ArrayList<>();static {suffixList.add("xls");suffixList.add("xlsx");/*suffixList.add("doc");suffixList.add("docx");suffixList.add("pdf");*/}/*** 解压缩rar** @param rarFilePath* @param targetPath* @param isInSameDir* @return*/public static List<String> unrar(String rarFilePath, String targetPath, boolean isInSameDir) {List<String> list = new ArrayList<>();StringBuffer msg = new StringBuffer();OutputStream os = null;InputStream is = null;ZipFile zipFile = null;logger.info("压缩包路径为:{}", rarFilePath);try {//File rarFile = new File(rarFilePath);//先解压到指定路径File directoryFile = new File(targetPath);if (!directoryFile.exists()) {directoryFile.mkdir();}String cmd = "unrar X -o+ " + rarFilePath + " " + targetPath;//解压logger.info("文件({})开始解压,开始时间:{}", rarFilePath, DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));ShellUtil.excuete(cmd);logger.info("文件({})结束解压,结束时间:{}", rarFilePath, DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));// 把解压后所有子目录的文件都移入目标目录if (isInSameDir) {String ret = moveToRootDir(targetPath);if (!StringUtils.isEmpty(ret)) {msg.setLength(0);msg.append(ret);}}//如果解压的文件在在目标文件夹中,将其删除/*if (rarFilePath.contains(targetPath)) {rarFile.delete();}*//*List<Map<String, String>> files = getFiles(targetPath, new ArrayList<>());if (!CollectionUtils.isEmpty(files)) {for (Map<String, String> map : files) {String fileName = map.get("fileName");String filePath = map.get("filePath");int i1 = fileName.lastIndexOf(".");String suffix = fileName.substring(i1 + 1);if (suffixList.contains(suffix)) {int i = filePath.lastIndexOf("\\");String path = filePath.substring(0, i + 1);File oldFile = new File(filePath);StringBuilder sb = new StringBuilder();String newFilePath = sb.append(path).append(tag).append(fileName).toString();logger.info("新文件路径:({})",newFilePath);oldFile.renameTo(new File(newFilePath));list.add(tag + fileName);}}}*///目标目录的全部文件/*File folder = new File(targetPath);File[] files = folder.listFiles();if (null != files) {//遍历文件夹下的所有文件for (int i = 0; i < files.length; i++) {File file = files[i];//如果是文件String name = file.getName();int index1 = name.indexOf(".");String suffix = name.substring(index1 + 1, name.length());if (file.length() > 0 && !suffix.equals("rar")) {File newFile = new File(targetPath + "/" + tag + file.getName());file.renameTo(newFile);list.add(newFile.getName());*//*String filePath = file.getPath();if (filePath.lastIndexOf(".") > -1) {//获取文件的后缀String suffix = filePath.substring(filePath.lastIndexOf("."), filePath.length()).toLowerCase();//如果是压缩包,继续解压缩,也就是解压到目标目录下没有rar文件位置if (filePath.lastIndexOf(".") > -1 && Arrays.asList(SUFFIX_NAMES).contains(suffix)) {String ret = unCompressedFilesToSameDir(filePath, targetPath, suffix);if (!StringUtils.isEmpty(ret)) {msg.setLength(0);msg.append(ret);}}}*//*}//如果是文件夹if (file.isDirectory()) {File fileFilder = new File(targetPath + File.separator + file.getName());if (!fileFilder.exists()) {fileFilder.mkdir();}}}}*/return list;} catch (Exception e) {logger.error(e.getMessage(), e);} finally {closeZipStream(zipFile, is, os);}return list;}/*** 移动目录下的所有文件到根目录** @param filePath*/public static String moveToRootDir(String filePath) {String msg = "";List<Map<String, String>> allList = new ArrayList<>();File baseFile = new File(filePath);if (baseFile.isDirectory()) {for (File file : baseFile.listFiles()) {if (file.isDirectory()) {getFiles(file.getAbsolutePath(), allList);}}}if (allList != null && allList.size() > 0) {for (int i = 0; i < allList.size(); i++) {//判断有没有重名的文件String fileName = allList.get(i).get("fileName");if (checkFileExistence(filePath, fileName)) {msg = "存在重复的文件名:" + fileName;}FileUtil.moveFile(allList.get(i).get("filePath"), filePath, fileName);}}return msg;}/*** 获取一个目录下所有路径** @param path* @param mapList* @return*/public static List<Map<String, String>> getFiles(String path, List<Map<String, String>> mapList) {File file = new File(path);Map<String, String> map = new HashMap<>(5);// 如果这个路径是文件夹if (file.isDirectory()) {// 获取路径下的所有文件File[] files = file.listFiles();for (int i = 0; i < files.length; i++) {// 如果还是文件夹 递归获取里面的文件 文件夹if (files[i].isDirectory()) {getFiles(files[i].getPath(), mapList);} else {map = new HashMap<>(5);map.put("fileName", files[i].getName());map.put("filePath", files[i].getAbsolutePath());mapList.add(map);}}} else {System.out.println("文件:" + file.getPath());}return mapList;}/*** 通过linux命令解压rar4以上版本的压缩包** @param rarFilePath* @param targetPath*/public static void unrarNewVersion(String rarFilePath, String targetPath) {File saveDir = new File(targetPath);if (!saveDir.exists()) {saveDir.mkdir();}String command = "unrar x -o+  " + rarFilePath + " " + targetPath;ShellUtil.excuete(command);}/*** 解压缩7z包** @param rarFilePath* @param targetPath* @param isInSameDir* @return*/public static String unSevenZ(String rarFilePath, String targetPath, boolean isInSameDir) {StringBuffer msg = new StringBuffer();try {SevenZFile sevenZFile = new SevenZFile(new File(rarFilePath));SevenZArchiveEntry entry = sevenZFile.getNextEntry();while (entry != null) {if (entry.isDirectory()) {new File(targetPath + File.separator + entry.getName()).mkdirs();entry = sevenZFile.getNextEntry();continue;}String sevenZFileName = entry.getName();if (isInSameDir) {if (sevenZFileName.indexOf(File.separator) > -1) {sevenZFileName = sevenZFileName.substring(sevenZFileName.lastIndexOf(File.separator), sevenZFileName.length());if (sevenZFileName.startsWith("~$")) {entry = sevenZFile.getNextEntry();continue;}}}if (checkFileExistence(targetPath, sevenZFileName)) {msg.setLength(0);msg.append("存在重复的文件名:" + sevenZFileName);}FileOutputStream out = new FileOutputStream(targetPath+ File.separator + sevenZFileName);byte[] content = new byte[(int) entry.getSize()];sevenZFile.read(content, 0, content.length);out.write(content);out.close();entry = sevenZFile.getNextEntry();if (sevenZFileName.lastIndexOf(".") > -1) {String suffix = sevenZFileName.substring(sevenZFileName.lastIndexOf("."), sevenZFileName.length()).toLowerCase();if (Arrays.asList(SUFFIX_NAMES).contains(suffix)) {String ret = unCompressedFilesToSameDir(targetPath + File.separator + sevenZFileName, targetPath, suffix);if (!StringUtils.isEmpty(ret)) {msg.setLength(0);msg.append(ret);}}}}sevenZFile.close();return msg.toString();} catch (FileNotFoundException e) {logger.error(e.getMessage(), e);} catch (IOException e) {logger.error(e.getMessage(), e);}return msg.toString();}/*** 构建目录** @param outputDir 输出目录* @param subDir    子目录*/public static void createDirectory(String outputDir, String subDir) {File file = new File(outputDir);// 子目录不为空if (!(subDir == null || "".equals(subDir.trim()))) {file = new File(outputDir + File.separator + subDir);}if (!file.exists()) {if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}file.mkdirs();}}/*** 解压缩文件到同一文件夹下* [.rar .zip .7z]** @param compressedFilePath* @param targetPath* @param suffix*/public static String unCompressedFilesToSameDir(String compressedFilePath, String targetPath, String suffix) {String msg = "";if (!StringUtils.isEmpty(suffix)) {suffix = suffix.toLowerCase();if (RAR.equals(suffix)) {FileUtil.unrar(compressedFilePath, targetPath, true);}if (ZIP.equals(suffix)) {msg = FileUtil.unzip(compressedFilePath, targetPath, true);}if (SEVEN_Z.equals(suffix)) {msg = FileUtil.unSevenZ(compressedFilePath, targetPath, true);}}return msg;}public static boolean fileToZip(String sourceFilePath, String zipFilePath, String fileName) {boolean flag = false;File sourceFile = new File(sourceFilePath);FileInputStream fis = null;BufferedInputStream bis = null;FileOutputStream fos = null;ZipOutputStream zos = null;if (sourceFile.exists() == false) {System.out.println("待压缩的文件目录:" + sourceFilePath + "不存在.");} else {try {File path = new File(zipFilePath);if (path.exists() == false) {path.mkdirs();}File zipFile = new File(zipFilePath + File.separator + fileName + ".zip");if (zipFile.exists()) {System.out.println(zipFilePath + "目录下存在名字为:" + fileName + ".zip" + "打包文件.");} else {fos = new FileOutputStream(zipFile);zos = new ZipOutputStream(new BufferedOutputStream(fos));recursion(zos, sourceFile, sourceFile, fileName);flag = true;}} catch (FileNotFoundException e) {logger.error(e.getMessage(), e);throw new RuntimeException(e);} catch (IOException e) {logger.error(e.getMessage(), e);throw new RuntimeException(e);} finally {//关闭流try {if (null != bis) {bis.close();}if (null != zos) {zos.close();}} catch (IOException e) {logger.error(e.getMessage(), e);throw new RuntimeException(e);}}}return flag;}private static void recursion(ZipOutputStream zos, File sourceFile, File basePath, String fileName) throws IOException {File[] sourceFiles = sourceFile.listFiles();FileInputStream fis = null;BufferedInputStream bis = null;try {if (null == sourceFiles || sourceFiles.length < 1 || null == basePath || basePath.exists() == false) {System.out.println("待压缩的文件目录:" + sourceFile.getPath() + "里面不存在文件,无需压缩.");} else {byte[] bufs = new byte[1024 * 10];for (int i = 0; i < sourceFiles.length; i++) {File file = sourceFiles[i];String pathName = file.getPath().substring(basePath.getPath().length() + 1);;if (file.isDirectory()) {zos.putNextEntry(new ZipEntry(pathName + File.separator));recursion(zos, file, basePath, fileName);} else {if (file.getName().contains(fileName)) {logger.info("存在重复的文件名:" + file.getName());continue;}//创建ZIP实体,并添加进压缩包ZipEntry zipEntry = new ZipEntry(pathName);zos.putNextEntry(zipEntry);//读取待压缩的文件并写进压缩包里int size = 1024 * 10;fis = new FileInputStream(file);bis = new BufferedInputStream(fis, size);int read = 0;while ((read = bis.read(bufs, 0, size)) != -1) {zos.write(bufs, 0, read);}}try {if (null != fis) {fis.close();}if (null != bis) {bis.close();}} catch (IOException e) {logger.error(e.getMessage(), e);}}}} finally {//关闭流try {if (null != fis) {fis.close();}if (null != bis) {bis.close();}} catch (IOException e) {logger.error(e.getMessage(), e);}}
//        }}/*** 复制文件夹下的所有文件夹或文件到另一个文件夹** @param oldPath* @param newPath* @throws IOException*/public static void copyDir(String oldPath, String newPath) throws IOException {File file = new File(oldPath);//文件名称列表String[] filePath = file.list();if (!(new File(newPath)).exists()) {(new File(newPath)).mkdir();}for (int i = 0; i < filePath.length; i++) {if ((new File(oldPath + File.separator + filePath[i])).isDirectory()) {copyDir(oldPath + File.separator + filePath[i], newPath + File.separator + filePath[i]);}if (new File(oldPath + File.separator + filePath[i]).isFile()) {copyFile(oldPath + File.separator + filePath[i], newPath + File.separator + filePath[i]);}}}public static void copyFile(String oldPath, String newPath) throws IOException {File oldFile = new File(oldPath);File file = new File(newPath);FileInputStream in = new FileInputStream(oldFile);FileOutputStream out = new FileOutputStream(file);byte[] buffer = new byte[2097152];while ((in.read(buffer)) != -1) {out.write(buffer);}}/*** 解压缩(支持分卷压缩解压)** @param zipFilePath 指定的ZIP压缩文件 路径* @param dest        解压目录* @param passwd      ZIP文件的密码 。需要解压密码时必须传入,否则传入null即可* @return 解压后文件名数组* @throws ZipException 压缩文件有损坏或者解压缩失败抛出*/public static ArrayList<File> unzipBySplit(String zipFilePath, String dest, String passwd) throws IOException, net.lingala.zip4j.exception.ZipException {File zipFile = new File(zipFilePath);net.lingala.zip4j.core.ZipFile zFile = new net.lingala.zip4j.core.ZipFile(zipFile);//设置编码格式zFile.setFileNameCharset("GBK");if (!zFile.isValidZipFile()) {throw new ZipException("压缩文件不合法,可能被损坏!");}File destDir = new File(dest);//判断是文件夹路径且不存在if (destDir.isDirectory() && !destDir.exists()) {destDir.mkdir();}//判断文件是否加密if (zFile.isEncrypted()) {if (StringUtils.isBlank(passwd)) {throw new ZipException("文件已加密,需要解压密码,解压密码不能为空!");} else {zFile.setPassword(passwd.toCharArray());}}//解压文件logger.info("文件({})开始解压,开始时间:{}", zipFilePath, DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));zFile.extractAll(dest);logger.info("文件({})结束解压,结束时间:{}", zipFilePath, DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));ArrayList<File> extractedFileList = new ArrayList<File>();List<FileHeader> headerList = zFile.getFileHeaders();if (headerList != null && headerList.size() > 0) {for (FileHeader fileHeader : headerList) {if (!fileHeader.isDirectory()) {//StringBuilder sb = new StringBuilder();/*String fileName = sb.append(tag).append(fileHeader.getFileName()).toString();File file = new File(dest + "/" + fileHeader.getFileName());file.renameTo(new File(dest + "/" + fileName));*/String fileName = fileHeader.getFileName();String newFilePath = null;int i = fileName.lastIndexOf(".");String newFileName = UUID.randomUUID().toString().replace("-", "") + fileName.substring(i);newFilePath =dest +File.separator + newFileName;if (fileName.contains("结算报告-审计表")) {newFilePath = dest + File.separator + "工程结算审计表";File newFile = new File(newFilePath);if (!newFile.exists()){newFile.mkdirs();}newFilePath = newFilePath + File.separator + newFileName;} else if (fileName.contains("审计汇总表")) {newFilePath = dest + File.separator + "工程结算审计汇总表";File newFile = new File(newFilePath);if (!newFile.exists()){newFile.mkdirs();}newFilePath = newFilePath + File.separator + newFileName;}File file = new File(dest + File.separator + fileName);File newFile = new File(newFilePath);file.renameTo(newFile);extractedFileList.add(newFile);}}}return  extractedFileList;/*String[] extractedFiles = new String[extractedFileList.size()];extractedFileList.toArray(extractedFiles);return extractedFiles;*/}/*** 压缩多个文件到一个压缩包中* @param srcFiles* @param zipFile* @param map*/public static void zipFiles(File[] srcFiles, File zipFile) {// 判断压缩后的文件存在不,不存在则创建if (!zipFile.exists()) {try {zipFile.createNewFile();} catch (IOException e) {e.printStackTrace();}}// 创建 FileOutputStream 对象FileOutputStream fileOutputStream = null;// 创建 ZipOutputStreamZipOutputStream zipOutputStream = null;// 创建 FileInputStream 对象FileInputStream fileInputStream = null;try {// 实例化 FileOutputStream 对象fileOutputStream = new FileOutputStream(zipFile);// 实例化 ZipOutputStream 对象zipOutputStream = new ZipOutputStream(fileOutputStream);// 创建 ZipEntry 对象ZipEntry zipEntry = null;// 遍历源文件数组for (int i = 0; i < srcFiles.length; i++) {// 将源文件数组中的当前文件读入 FileInputStream 流中fileInputStream = new FileInputStream(srcFiles[i]);// 实例化 ZipEntry 对象,源文件数组中的当前文件System.out.println(srcFiles[i].getPath()+"------"+srcFiles[i].getName());zipEntry = new ZipEntry(srcFiles[i].getName());zipOutputStream.putNextEntry(zipEntry);// 该变量记录每次真正读的字节个数int len;// 定义每次读取的字节数组byte[] buffer = new byte[1024];while ((len = fileInputStream.read(buffer)) > 0) {zipOutputStream.write(buffer, 0, len);}}zipOutputStream.closeEntry();zipOutputStream.close();fileInputStream.close();fileOutputStream.close();} catch (IOException e) {e.printStackTrace();logger.error(e.getMessage(), e);}}public static void main(String[] args) throws IOException {try {File[] srcFiles = {new File("C:\\Users\\321\\Desktop\\engFinal.json"), new File("C:\\Users\\321\\Desktop\\123\\engneer2.json"), new File("C:\\Users\\321\\Desktop\\123\\engSettlement.json")};File zipFile = new File("C:\\Users\\秦齐锋\\Desktop\\123\\ZipFile.zip");// 调用压缩方法zipFiles(srcFiles, zipFile);System.out.println(zipFile);//fileToZip("C:\\Users\\321\\Desktop\\123","C:\\Users\\321\\Desktop","1234");//unzipBySplit("D:\\file\\2021\\6\\6\\【SettlBody】新建文件夹 (2).zip", "D:\\file\\2021\\6\\6\\", null);} catch (Exception e) {e.printStackTrace();}}
}

Java代码实现解压文件包和压缩文件的工具类相关推荐

  1. 如何用WinRAR解压.7z.00x分卷压缩文件

    如何用WinRAR解压.7z.00x分卷压缩文件   在win10操作系统中,在D:\Test\test的目录下有若干test.7z.00x分卷压缩文件(后缀从001到00x),下面以test.7z. ...

  2. android assets解压,Android assets内压缩文件解压,解压到缓存示例

    1.assets内压缩文件解压AssetsZipUtils,包含一个获取文件夹下所有文件路径的方法,方便获取文件使用 public class AssetsZipUtils { public stat ...

  3. java代码实现解压文件_Java压缩/解压文件的实现代码

    用java压缩/解压文件: import java.io.*; import java.awt.*; import java.awt.event.*; import java.util.*; impo ...

  4. java解压zip包_Java中文件的压缩与解压,每天进步一点点系列

    使用java.util.zip包,实现文件的压缩与解压,并提供了下载方法 注意 无论是调用createNewFile()创建文件,还是在创建输出流时由输出流负责创建文件,都必须保证父路径已经存在,否则 ...

  5. java如何压缩解压图片_Java实现压缩文件与解压缩文件

    由于工作需要,需要将zip的压缩文件进行解压,经过调查发现,存在两个开源的工具包,一个是Apache的ant工具包,另一个就是Java api自带的工具包:但是Java自带的工具包存在问题:如果压缩或 ...

  6. java解压zip_Java实现zip压缩文件的解压

    需求描述: 前段时间写了一篇博客<Java实现对文本文件MD5加密并ftp传送到远程主机目录>,实现了一部分的业务需求.然而有些业务可能不止传送一个文件,有时候客户需要传多个文件,原有系统 ...

  7. tar只解压tar包中某个文件

    如果tar包很大,而只想解压出其中某个文件.方法如下: 只想解压出Redis-1.972.tar  中的Changes文件,来查看有哪些更改. [root@uplooking]# tar -tf Re ...

  8. Python解压常见格式的压缩文件

    网络下载的视频文件通常都是压缩文件,以 rar 格式诸多.为了方便在 Android 系统中播放,所以想一次性将某个文件夹的文件全部解压.以下代码能对 rar, zip, gz, tgz 和 tar ...

  9. 关于使用zip4j实现解压与压缩文件,以及向压缩文件中添加文件 , 解压带密码的压缩文件 , 向压缩文件添加密码

    解压与压缩文件 1.Zip4j介绍 zip4j官网:http://www.lingala.net/zip4j/ 可以在"download"页面下载官方示例进行学习. 特征: 从Zi ...

最新文章

  1. python 内置函数map的使用
  2. 美团应届生年薪达 35 万?究竟什么导致薪资倒挂?
  3. 更改WSSv3站点集访问地址
  4. Spring EL bean引用实例
  5. Scala入门到精通——第二十二节 高级类型 (一)
  6. 项目管理最佳实践方法_项目管理最佳实践,企业如何进行有效的项目管理
  7. linux 自学系列:touch 命令
  8. aix-裸设备文件大小查看
  9. 问卷设计与统计分析——常用的量表
  10. linux ftp解压命令 cannot fid or open,CPAN命令操作细节
  11. oracle10g数据库复制,windows 下oracle 10G 数据库移植到 linux平台 (通过文件直接复制方法)...
  12. 如何在云服务器上跑深度学习的代码?(ResNet50为例)
  13. html百度天气查询api,百度提供天气预报查询接口API
  14. 语音特征提取 matlab,基于matlab的语音信号特征提取方法研究
  15. 干货!如何在SCI论文中转述和总结别人的论文和成果
  16. 模拟电路44(深度负反馈条件下的近似计算)
  17. 77:88火箭输了(阿尔德里奇=罗伊)
  18. 孩子不是两人婚姻的砝码
  19. openwrt+Linkit7688+wm8960:粗略实现wm8960耳麦和喇叭音频输出
  20. [梳理]两种价值函数

热门文章

  1. echarts柱状图上增加icon图标
  2. 机器学习吴恩达——第一周
  3. springboot-vue跨域详解
  4. 基于爬虫的诗人APP
  5. matlab学习,mathematics学习
  6. 第五届双态IT北京用户大会 | 倒计时2天!大佬云集!
  7. SpringBoot 微信退款申请
  8. 408王道计算机组成原理强化——数据的运算及大题
  9. 对 RNN 中 BPTT 求导过程的解析尝试
  10. Unity模拟3D飞机驾驶(稳定版和灵活版)