1. // java批量解压文件夹下的所有压缩文件(.rar、.zip、.gz、.tar.gz)

新建工具类:

  1.  
  1. package com.mobile.utils;
  2.  
  3. import com.github.junrar.Archive;
    import com.github.junrar.rarfile.FileHeader;
    import org.apache.tools.tar.TarEntry;
    import org.apache.tools.tar.TarInputStream;
  4.  
  5. import java.io.*;
    import java.nio.charset.Charset;
    import java.util.Enumeration;
    import java.util.zip.GZIPInputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
  6.  
  7. /**
    * @Description: UnzipUtil 工具类
    * @Param:
    * @return:
    * @Author: mufeng
    * @Date: 2018/8/20
    */
    public class UnzipUtil {
  8.  
  9. //解压.zip文件
    public static void unZip(String sourceFile, String outputDir) throws IOException {
    ZipFile zipFile = null;
    File file = new File(sourceFile);
    try {
    Charset CP866 = Charset.forName("CP866"); //specifying alternative (non UTF-8) charset
    zipFile = new ZipFile(file, CP866);
    createDirectory(outputDir,null);//创建输出目录
  10.  
  11. Enumeration<?> enums = zipFile.entries();
    while(enums.hasMoreElements()){
  12.  
  13. ZipEntry entry = (ZipEntry) enums.nextElement();
    System.out.println("解压." + entry.getName());
  14.  
  15. if(entry.isDirectory()){//是目录
    createDirectory(outputDir,entry.getName());//创建空目录
    }else{//是文件
    File tmpFile = new File(outputDir + "/" + entry.getName());
    createDirectory(tmpFile.getParent() + "/",null);//创建输出目录
  16.  
  17. InputStream in = null;
    OutputStream out = null;
    try{
    in = zipFile.getInputStream(entry);;
    out = new FileOutputStream(tmpFile);
    int length = 0;
  18.  
  19. byte[] b = new byte[2048];
    while((length = in.read(b)) != -1){
    out.write(b, 0, length);
    }
  20.  
  21. }catch(IOException ex){
    throw ex;
    }finally{
    if(in!=null)
    in.close();
    if(out!=null)
    out.close();
    }
    }
    }
  22.  
  23. } catch (IOException e) {
    throw new IOException("解压缩文件出现异常",e);
    } finally{
    try{
    if(zipFile != null){
    zipFile.close();
    }
    }catch(IOException ex){
    throw new IOException("关闭zipFile出现异常",ex);
    }
    }
    }
  24.  
  25. /**
    * 构建目录
    * @param outputDir
    * @param subDir
    */
    public static void createDirectory(String outputDir,String subDir){
    File file = new File(outputDir);
    if(!(subDir == null || subDir.trim().equals(""))){//子目录不为空
    file = new File(outputDir + "/" + subDir);
    }
    if(!file.exists()){
    if(!file.getParentFile().exists())
    file.getParentFile().mkdirs();
    file.mkdirs();
    }
    }
  26.  
  27. //解压.rar文件
    public static void unRar(String sourceFile, String outputDir) throws Exception {
    Archive archive = null;
    FileOutputStream fos = null;
    File file = new File(sourceFile);
    try {
    archive = new Archive(file);
    FileHeader fh = archive.nextFileHeader();
    int count = 0;
    File destFileName = null;
    while (fh != null) {
    System.out.println((++count) + ") " + fh.getFileNameString());
    String compressFileName = fh.getFileNameString().trim();
    destFileName = new File(outputDir + "/" + compressFileName);
    if (fh.isDirectory()) {
    if (!destFileName.exists()) {
    destFileName.mkdirs();
    }
    fh = archive.nextFileHeader();
    continue;
    }
    if (!destFileName.getParentFile().exists()) {
    destFileName.getParentFile().mkdirs();
    }
    fos = new FileOutputStream(destFileName);
    archive.extractFile(fh, fos);
    fos.close();
    fos = null;
    fh = archive.nextFileHeader();
    }
  28.  
  29. archive.close();
    archive = null;
    } catch (Exception e) {
    throw e;
    } finally {
    if (fos != null) {
    try {
    fos.close();
    fos = null;
    } catch (Exception e) {
    //ignore
    }
    }
    if (archive != null) {
    try {
    archive.close();
    archive = null;
    } catch (Exception e) {
    //ignore
    }
    }
    }
    }
  30.  
  31. //解压.gz文件
    public static void unGz(String sourceFile, String outputDir) {
    String ouputfile = "";
    try {
    //建立gzip压缩文件输入流
    FileInputStream fin = new FileInputStream(sourceFile);
    //建立gzip解压工作流
    GZIPInputStream gzin = new GZIPInputStream(fin);
    //建立解压文件输出流
    /*ouputfile = sourceFile.substring(0,sourceFile.lastIndexOf('.'));
    ouputfile = ouputfile.substring(0,ouputfile.lastIndexOf('.'));*/
    File file = new File(sourceFile);
    String fileName = file.getName();
    outputDir = outputDir + "/" + fileName.substring(0, fileName.lastIndexOf('.'));
    FileOutputStream fout = new FileOutputStream(outputDir);
  32.  
  33. int num;
    byte[] buf=new byte[1024];
  34.  
  35. while ((num = gzin.read(buf,0,buf.length)) != -1)
    {
    fout.write(buf,0,num);
    }
  36.  
  37. gzin.close();
    fout.close();
    fin.close();
    } catch (Exception ex){
    System.err.println(ex.toString());
    }
    return;
    }
  38.  
  39. //解压.tar.gz文件
    public static void unTarGz(String sourceFile,String outputDir) throws IOException{
    TarInputStream tarIn = null;
    File file = new File(sourceFile);
    try{
    tarIn = new TarInputStream(new GZIPInputStream(
    new BufferedInputStream(new FileInputStream(file))),
    1024 * 2);
  40.  
  41. createDirectory(outputDir,null);//创建输出目录
  42.  
  43. TarEntry entry = null;
    while( (entry = tarIn.getNextEntry()) != null ){
  44.  
  45. if(entry.isDirectory()){//是目录
    entry.getName();
    createDirectory(outputDir,entry.getName());//创建空目录
    }else{//是文件
    File tmpFile = new File(outputDir + "/" + entry.getName());
    createDirectory(tmpFile.getParent() + "/",null);//创建输出目录
    OutputStream out = null;
    try{
    out = new FileOutputStream(tmpFile);
    int length = 0;
  46.  
  47. byte[] b = new byte[2048];
  48.  
  49. while((length = tarIn.read(b)) != -1){
    out.write(b, 0, length);
    }
  50.  
  51. }catch(IOException ex){
    throw ex;
    }finally{
  52.  
  53. if(out!=null)
    out.close();
    }
    }
    }
    }catch(IOException ex){
    throw new IOException("解压归档文件出现异常",ex);
    } finally{
    try{
    if(tarIn != null){
    tarIn.close();
    }
    }catch(IOException ex){
    throw new IOException("关闭tarFile出现异常",ex);
    }
    }
    }
  54.  
  55. public static void main(String[] args) throws Exception {
    //测试解压文件(1. .zip 2. .rar 3. .gz 4. .tar.gz)
    String gzPath = "E:\\project11_LogAnalysis\\dc.weilianupup.com_2018_08_07_110000_120000.gz";
    String zipPath = "E:\\project11_LogAnalysis\\Shadowsocks-3.4.3.zip";
    String tarGzPath = "E:\\project11_LogAnalysis\\nginx-1.12.0.tar.gz";
    String rarPath = "E:\\project11_LogAnalysis\\test.rar";
  56.  
  57. String outputDir = "E:\\project11_LogAnalysis\\test";
  58.  
  59. // 传入参数(待解压的压缩文件路径, 解压文件到的目标文件夹)
    // unZip(zipPath, outputDir);
    // unGz(gzPath, outputDir);
    // unTarGz(tarGzPath, outputDir);
    unRar(rarPath, outputDir);
  60.  
  61. }
  62.  
  63. }
  1.  

调用工具类,实现批量解压:

  1. package com.mobile.web.api;
  2.  
  3. import com.mobile.commons.JsonResp;
  4. import com.mobile.model.LogInfo;
  5. import com.mobile.service.LogInfoService;
  6. import com.mobile.utils.UnzipUtil;
  7. import org.apache.commons.lang3.StringUtils;
  8. import org.apache.log4j.Logger;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.transaction.annotation.Transactional;
  11. import org.springframework.web.bind.annotation.RequestBody;
  12. import org.springframework.web.bind.annotation.RequestMapping;
  13. import org.springframework.web.bind.annotation.RequestMethod;
  14. import org.springframework.web.bind.annotation.RestController;
  15.  
  16. import java.io.*;
  17. import java.text.ParseException;
  18. import java.text.SimpleDateFormat;
  19. import java.util.*;
  20.  
  21. @RestController
  22. @RequestMapping(value = "/test")
  23. @Transactional
  24. public class ImportController {
  25. Logger log = Logger.getLogger(this.getClass());
  26.  
  27. @Autowired
  28. private LogInfoService logInfoService;
  29.  
  30. @RequestMapping(value = "/unZipFiles", method = RequestMethod.POST)
  31. public JsonResp unZipFiles(@RequestBody Map map) throws Exception {
  32. log.debug("批量解压指定文件夹下的压缩文件文件至另一指定文件夹下");
  33.  
  34. String sourceDir = map.get("sourceDir").toString();
  35. String outputDir = map.get("outputDir").toString();
  36. File file = new File(sourceDir);
  37. List<File> sourceFile = new ArrayList();
  38. listFiles(file, sourceFile);
  39. for (File file2 : sourceFile){
  40. String fileName = file2.getName();
  41. String fileType = fileName.substring(fileName.lastIndexOf("."));
  42. if (".gz".equals(fileType)){
  43. fileName = fileName.substring(0, fileName.lastIndexOf("."));
  44. String fileType2 = fileName.substring(fileName.lastIndexOf("."));
  45. if (".tar".equals(fileType2)){
  46. fileType = ".tar.gz";
  47. }
  48. }
  49. String fileSource = file2.getAbsolutePath();
  50. switch(fileType){
  51. case ".gz" : UnzipUtil.unGz(fileSource, outputDir); break; //解压压缩文件
  52. case ".zip" : UnzipUtil.unZip(fileSource, outputDir); break;
  53. case ".tar.gz" : UnzipUtil.unTarGz(fileSource, outputDir); break;
  54. case ".rar" : UnzipUtil.unRar(fileSource, outputDir); break; //解压rar文件时,暂时有问题
  55. default: log.debug(fileSource + ": 此文件无法解压");
  56. }
  57. // file2.delete(); //解压完后,是否删除
  58. }
  59. return JsonResp.ok();
  60. }
  61.  
  62. //循环出文件夹下的所有压缩文件
  63. public static void listFiles(File file, List<File> sourceFile){
  64.  
  65. if(file.isDirectory()){
  66. File[] files = file.listFiles();
  67. for (File file1 : files){
  68. if(file1.isDirectory()){ //若是目录,则递归该目录下的文件
  69. listFiles(file1, sourceFile);
  70. }else if (file1.isFile()){
  71. sourceFile.add(file1); //若是文件,则保存
  72. }
  73. }
  74. }
  75.  
  76. }

使用到的maven依赖:

  1.      <dependency>
  2. <groupId>org.apache.ant</groupId>
  3. <artifactId>ant</artifactId>
  4. <version>1.8.1</version>
  5. </dependency>
  6.  
  7. <dependency>
  8. <groupId>com.github.junrar</groupId>
  9. <artifactId>junrar</artifactId>
  10. <version>0.7</version>
  11. </dependency>

参考: https://www.cnblogs.com/scw2901/p/4379143.html

       https://blog.csdn.net/u012100371/article/details/75029961

java批量解压文件夹下的所有压缩文件(.rar、.zip、.gz、.tar.gz)的更多相关文章

  1. 【bat批处理】批量执行某个文件夹下的所有sql文件bat批处理

    遍历文件夹下所有的sql文件,然后命令行执行 for /r "D:\yonyou\UBFV60\U9.VOB.Product.Other" %%a in (*.sql) do ( ...

  2. android XMl 解析神奇xstream 一: 解析android项目中 asset 文件夹 下的 aa.xml 文件

    简介 XStream 是一个开源项目,一套简单实用的类库,用于序列化对象与 XML 对象之间的相互转换. 将 XML 文件内容解析为一个对象或将一个对象序列化为 XML 文件. 1.下载工具 xstr ...

  3. 读取同一文件夹下多个txt文件中的特定内容并做统计

    读取同一文件夹下多个txt文件中的特定内容并做统计 有网友在问,C#读取同一文件夹下多个txt文件中的特定内容,并把各个文本的数据做统计. 昨晚Insus.NET抽上些少时间,来实现此问题,加强自身的 ...

  4. C#_IO操作_查询指定文件夹下的每个子文件夹占空间的大小

    1.前言 磁盘内存用掉太多,想查那些文件夹占的内存比较大,再找出没有用的文件去删除. 2.代码 static void Main(string[] args) { while (true) { //指 ...

  5. 将文件夹下的所有csv文件存入数据库

    # 股票的多因子分层回测代码实现 import os import pymysql # import datetime, time # from config import * database_ta ...

  6. linux 系统获得当前文件夹下存在的所有文件 scandir函数和struct dirent **namelist结构体[转]

    linux 系统获得当前文件夹下存在的所有文件 scandir函数和struct dirent **namelist结构体 1.引用头文件#include<dirent.h> struct ...

  7. MATLAB读取一个文件夹下的多个子文件夹中的多个指定格式的文件

    MATLAB需要读取一个文件夹下的多个子文件夹中的指定格式文件,这里以读取*.JPG格式的文件为例 1.首先确定包含多个子文件夹的总文件夹 maindir = 'C:\Temp Folder'; 2. ...

  8. MapReduce会自动忽略文件夹下的.开头的文件

    MapReduce会自动忽略文件夹下的.开头的文件,跳过这些文件的处理.

  9. java解压多层目录中多个压缩文件和处理压缩文件中有内层目录的情况

    代码: package com.xiaobai; import java.io.File; import java.io.FileOutputStream; import java.io.IOExce ...

随机推荐

  1. 查看MySQL语句变量了多少行数据

    explain MySQL语句 列如 explain SELECT * FROM 表名 WHERE id=1;

  2. C语言常用数据类型说明

     1.取值范围: short一般占两个字节,取值范围:-32768 - 32767   int一般占两个或四个字节,取值范围:-2147483648 - 2147483647 unsigned int ...

  3. python模块:sys

    # encoding: utf-8 # module sys # from (built-in) # by generator 1.145 """ This module ...

  4. Effective C++ 随笔(3)

    条款12: 以对象管理资源 两种只能指针: std:auto_ptr<> 当使用copy操作室,原先的智能指针指向为null std:tr1:share_ptr<int> sp ...

  5. Linux远程批量工具mooon_ssh和mooon_upload使用示例

    目录 目录 1 1. 前言 1 2. 批量执行命令工具:mooon_ssh 2 3. 批量上传文件工具:mooon_upload 2 4. 使用示例 3 4.1. 使用示例1:上传/etc/hosts ...

  6. android-基础编程-democoderjoy-架构篇

    设计这个demo很简单,针对每个控件放到一个listitem中去,主activity继承之listActivity,这样再override其单击效果进入到每个控件. 主界面流程 1.继承 MainAc ...

  7. wc2016鏖战表达式(可持久treap)

    由运算符有优先级可以想到先算优先级小的,然后两边递归,但符号比较少,有大量相同的,同级之间怎么办呢?因为运算符满足结合律,同级之间选一个然后两边递归也是没问题的,然后我们想到用fhqtreap进行维护 ...

  8. mach_absolute_time 使用

    今天看荣哥时间常用函数封装里有个不常见的函数 ,mach_absolute_time() ,经查询后感觉是个不错的函数,网上关于这个函数搜索以后简单整理来一下. 什么事Mach? 时间例程依赖于所需要 ...

  9. 关于git的ssh permission denied原因汇总

    SSH关于公钥认证Permission denied (publickey,gssapi-with-mic的问题 http://h2appy.blog.51cto.com/609721/1112797 ...

  10. 10.DataGrid的特性