zip、tar、tar.gz、rar的 java代码解压出文件夹,支持linux、windows系统

it2025-08-07  9

zip、tar、tar.gz、rar的 java代码解压,支持linux、windows系统

import lombok.extern.slf4j.Slf4j; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.compressors.xz.XZUtils; import org.apache.commons.compress.utils.IOUtils; import org.apache.log4j.Logger; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; import org.springframework.beans.factory.annotation.Value; import java.io.*; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Enumeration; import java.util.zip.GZIPInputStream; import java.util.Scanner; import java.util.concurrent.TimeUnit; @Slf4j public class ZipUtils {     static String upload_path = "yourUploadPath";     public static Logger logger = Logger.getLogger(ZipUtils.class);     public ZipUtils() {     }

    /**      * @return void      * @Description //TODO  支持zip解压(支持linux、windows系统)      * @Param [sourcefiles, decompreDirectory]      **/     @SuppressWarnings("unchecked")     public static void unZip(String sourcefiles, String decompreDirectory) throws IOException {         String newName = new File(sourcefiles).getName();         newName = newName.substring(0, newName.indexOf("."));         decompreDirectory = decompreDirectory + File.separator + newName;         ZipFile readfile = null;         log.info(ZipUtils.class+"--zip 解压开始");         try {             readfile = new ZipFile(sourcefiles);             Enumeration takeentrie = readfile.getEntries();             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;                 }

            }             log.info(ZipUtils.class+"--zip 解压完成");         } catch (IOException ex) {             ex.printStackTrace();             throw new IOException("解压失败:" + ex.toString());         } finally {             if (readfile != null) {                 try {                     readfile.close();                 } catch (IOException ex) {                     ex.printStackTrace();                     throw new IOException("解压失败:" + ex.toString());                 }             }         }     }

    /**      * @return void      * @Description //TODO  支持tar、 tar.gz的解压,暂时不支持tar.xz(windows环境下支持,Linux环境下不支持)      * @Date 16:48 2020/10/15      * @Param [sourceTarPath, FilePath]      **/

    public static void unTar(String sourceTarPath, String FilePath) {         File tarFile = new File(sourceTarPath);         File localFile = new File(FilePath);         TarArchiveEntry[] subEntries = null;         File subEntryFile = null;         if (!localFile.exists()) {             localFile.mkdir();         }         ArrayList<ZipFile> list = new ArrayList<ZipFile>();         ArchiveInputStream archiveInputStream = null;         try {             String orginFileName = tarFile.getName();             if (orginFileName.endsWith(".tar.gz")) {                 archiveInputStream = new ArchiveStreamFactory()                         .createArchiveInputStream("tar", new GZIPInputStream(new BufferedInputStream(new FileInputStream(tarFile))));             } else if (orginFileName.endsWith(".tar.xz")) {                 String tarFileName = XZUtils.getUncompressedFilename(sourceTarPath);                 tarFile = new File(tarFileName);                 archiveInputStream = new ArchiveStreamFactory()                         .createArchiveInputStream("tar", new BufferedInputStream(new FileInputStream(tarFile)));             } else if (orginFileName.endsWith(".tar")) {                 archiveInputStream = new ArchiveStreamFactory()                         .createArchiveInputStream("tar", new BufferedInputStream(new FileInputStream(tarFile)));             }             TarArchiveEntry entry = null;             FileInputStream fis = new FileInputStream(sourceTarPath);             TarArchiveInputStream taris = new TarArchiveInputStream(fis);             log.info(ZipUtils.class+"tar系列 解压开始");             while ((entry = (TarArchiveEntry) archiveInputStream.getNextEntry()) != null) {                 StringBuilder entryFileName = new StringBuilder();                 entryFileName.append(FilePath).append(File.separator).append(entry.getName());                 File entryFile = new File(entryFileName.toString());                 if (entry.isDirectory()) {                     if (!entryFile.exists()) {                         entryFile.mkdir();                     }                     subEntries = entry.getDirectoryEntries();                     for (int i = 0; i < subEntries.length; i++) {                         try (OutputStream out = new FileOutputStream(subEntryFile)) {                             subEntryFile = new File(entryFileName + File.separator + subEntries[i].getName());                             IOUtils.copy(taris, out);                         } catch (Exception e) {                             e.printStackTrace();                         }                     }                 } else {                     checkFileExists(entryFile);                     OutputStream out = new FileOutputStream(entryFile);                     IOUtils.copy(taris, out);                     out.close();                     //如果是gz文件进行递归解压                     unTar(entryFile.getPath(), FilePath);                 }

            }             log.info(ZipUtils.class+"tar系列 解压完成");         } catch (Exception e) {             logger.error(sourceTarPath + "parsing exceptions:", e);         } finally {             try {                 if (archiveInputStream != null) {                     archiveInputStream.close();                 }             } catch (Exception ex) {                 logger.error("close archiveInputStream exception:", ex);             }         }     }     public static void checkFileExists(File file) {         //判断是否是目录         if (file.isDirectory()) {             if (!file.exists()) {                 file.mkdir();             }         } else {             //判断父目录是否存在,如果不存在,则创建             if (file.getParentFile() != null && !file.getParentFile().exists()) {                 file.getParentFile().mkdirs();             }             try {                 file.createNewFile();             } catch (IOException e) {                 e.printStackTrace();             }         }     }

    /**      * @Description //TODO 支持rar的解压(需要引入winrar.exe程序,放入target目录)      * @Date 9:35 2020/10/16      * @Param [sourceRarPath, destDir] sourceRar 需要解压的rar文件全路径;destDir 需要解压到的文件目录      * @return void      **/     public static Boolean unRar(String sourceRarPath, String destDir) {         File zipFile = new File(sourceRarPath);         // 解决路径中存在/..格式的路径问题         File localFile = new File(destDir);         if (localFile.exists()) {             FileUtil.deleteDir(destDir);         }         localFile.mkdir();         while(destDir.contains("..")) {             String[] sepList = destDir.split("\\\\");             destDir = "";             for (int i = 0; i < sepList.length; i++) {                 if(!"..".equals(sepList[i]) && i < sepList.length -1 && "..".equals(sepList[i+1])) {                     i++;                 } else {                     destDir += sepList[i] + File.separator;                 }             }         }         // 获取WinRAR.exe的路径,放在java web工程下的WebRoot路径下         String classPath = "";         try {             classPath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath();         } catch (URISyntaxException e1) {             e1.printStackTrace();         }         // 兼容main方法执行和javaweb下执行         String winrarPath = (classPath.indexOf("WEB-INF") > -1 ? classPath.substring(0, classPath.indexOf("WEB-INF")) :                 classPath.substring(0, classPath.indexOf("classes"))) + "/WinRAR/WINRar.exe";         winrarPath = new File(winrarPath).getAbsoluteFile().getAbsolutePath();         boolean bool = false;         if (!zipFile.exists()) {             return false;         }         // 开始调用命令行解压         String cmd = winrarPath + " x " + zipFile + " " + destDir;         Runtime runtime = Runtime.getRuntime();         try {             Process p = runtime.exec(cmd);             log.info(ZipUtils.class+"rar 解压开始");             BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream(),"UTF-8"));             String line = reader.readLine();             while(line!=null) {                 logger.info(line);                 line = reader.readLine();             }             log.info(ZipUtils.class+"rar 解压完成");             reader.close();             if(p.waitFor()!=0) {                 return false;             }         } catch (IOException e) {             e.printStackTrace();         } catch (InterruptedException e) {             e.printStackTrace();         }         return true;     }

    /**      * @Description //TODO 调用linux命令解压(linux环境下支持--需要安装相关命令环境)      * @Date 9:45 2020/10/19      * @Param [proPath] 压缩包绝对路径      * @return java.lang.String      **/     public static String run(String zip_path) throws IOException {         String localFilePath = zip_path.substring(0, zip_path.indexOf("."));         File localFile = new File(localFilePath);         if (localFile.exists()) {             FileUtil.deleteDir(localFilePath);         }         localFile.mkdir();         String[] command = new String[3];         String zipInfo = "";         if (zip_path.endsWith(".tar.gz")) {             log.info(ZipUtils.class+"--.tar.gz 解压开始");             zipInfo = ".tar.gz";             command = new String[]{"/bin/sh", "-c", "tar -zxvf " + zip_path + " -C " + localFilePath};         } else if (zip_path.endsWith(".tar")) {             log.info(ZipUtils.class+"--.tar 解压开始");             zipInfo = ".tar";             command = new String[]{"/bin/sh", "-c", "tar xvf " + zip_path + " -C " + localFilePath};         } else if (zip_path.endsWith(".rar")) {             log.info(ZipUtils.class+"--.rar 解压开始");             zipInfo = ".rar";             command = new String[]{"/bin/sh", "-c", "unrar e " + zip_path + "  " + localFilePath};         }         Scanner input = null;         String result = "";         Process process = null;         try {             process = Runtime.getRuntime().exec(command);             try {                 //等待命令执行完成                 process.waitFor(15, TimeUnit.SECONDS);                 log.info(ZipUtils.class+"--"+zipInfo+"  解压完成");             } catch (InterruptedException e) {                 e.printStackTrace();                 log.info(ZipUtils.class+"--"+zipInfo+"  解压失败");             }             InputStream is = process.getInputStream();             input = new Scanner(is);             while (input.hasNextLine()) {                 result += input.nextLine() + "\n";             }             result = command + "\n" + result; //加上命令本身,打印出来         } finally {             if (input != null) {                 input.close();             }             if (process != null) {                 process.destroy();             }         }         return result;     } }

最新回复(0)