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

新建工具类:


package com.mobile.utils;

import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream; 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; /**
* @Description: UnzipUtil 工具类
* @Param:
* @return:
* @Author: mufeng
* @Date: 2018/8/20
*/
public class UnzipUtil { //解压.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);//创建输出目录 Enumeration<?> enums = zipFile.entries();
while(enums.hasMoreElements()){ ZipEntry entry = (ZipEntry) enums.nextElement();
System.out.println("解压." + entry.getName()); if(entry.isDirectory()){//是目录
createDirectory(outputDir,entry.getName());//创建空目录
}else{//是文件
File tmpFile = new File(outputDir + "/" + entry.getName());
createDirectory(tmpFile.getParent() + "/",null);//创建输出目录 InputStream in = null;
OutputStream out = null;
try{
in = zipFile.getInputStream(entry);;
out = new FileOutputStream(tmpFile);
int length = 0; byte[] b = new byte[2048];
while((length = in.read(b)) != -1){
out.write(b, 0, length);
} }catch(IOException ex){
throw ex;
}finally{
if(in!=null)
in.close();
if(out!=null)
out.close();
}
}
} } catch (IOException e) {
throw new IOException("解压缩文件出现异常",e);
} finally{
try{
if(zipFile != null){
zipFile.close();
}
}catch(IOException ex){
throw new IOException("关闭zipFile出现异常",ex);
}
}
} /**
* 构建目录
* @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();
}
} //解压.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();
} 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
}
}
}
} //解压.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); int num;
byte[] buf=new byte[1024]; while ((num = gzin.read(buf,0,buf.length)) != -1)
{
fout.write(buf,0,num);
} gzin.close();
fout.close();
fin.close();
} catch (Exception ex){
System.err.println(ex.toString());
}
return;
} //解压.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); createDirectory(outputDir,null);//创建输出目录 TarEntry entry = null;
while( (entry = tarIn.getNextEntry()) != null ){ 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; byte[] b = new byte[2048]; while((length = tarIn.read(b)) != -1){
out.write(b, 0, length);
} }catch(IOException ex){
throw ex;
}finally{ 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);
}
}
} 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"; String outputDir = "E:\\project11_LogAnalysis\\test"; // 传入参数(待解压的压缩文件路径, 解压文件到的目标文件夹)
// unZip(zipPath, outputDir);
// unGz(gzPath, outputDir);
// unTarGz(tarGzPath, outputDir);
unRar(rarPath, outputDir); } }

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

package com.mobile.web.api;

import com.mobile.commons.JsonResp;
import com.mobile.model.LogInfo;
import com.mobile.service.LogInfoService;
import com.mobile.utils.UnzipUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*; @RestController
@RequestMapping(value = "/test")
@Transactional
public class ImportController {
Logger log = Logger.getLogger(this.getClass()); @Autowired
private LogInfoService logInfoService; @RequestMapping(value = "/unZipFiles", method = RequestMethod.POST)
public JsonResp unZipFiles(@RequestBody Map map) throws Exception {
log.debug("批量解压指定文件夹下的压缩文件文件至另一指定文件夹下"); String sourceDir = map.get("sourceDir").toString();
String outputDir = map.get("outputDir").toString();
File file = new File(sourceDir);
List<File> sourceFile = new ArrayList();
listFiles(file, sourceFile);
for (File file2 : sourceFile){
String fileName = file2.getName();
String fileType = fileName.substring(fileName.lastIndexOf("."));
if (".gz".equals(fileType)){
fileName = fileName.substring(0, fileName.lastIndexOf("."));
String fileType2 = fileName.substring(fileName.lastIndexOf("."));
if (".tar".equals(fileType2)){
fileType = ".tar.gz";
}
}
String fileSource = file2.getAbsolutePath();
switch(fileType){
case ".gz" : UnzipUtil.unGz(fileSource, outputDir); break; //解压压缩文件
case ".zip" : UnzipUtil.unZip(fileSource, outputDir); break;
case ".tar.gz" : UnzipUtil.unTarGz(fileSource, outputDir); break;
case ".rar" : UnzipUtil.unRar(fileSource, outputDir); break; //解压rar文件时,暂时有问题
default: log.debug(fileSource + ": 此文件无法解压");
}
// file2.delete(); //解压完后,是否删除
}
return JsonResp.ok();
} //循环出文件夹下的所有压缩文件
public static void listFiles(File file, List<File> sourceFile){ if(file.isDirectory()){
File[] files = file.listFiles();
for (File file1 : files){
if(file1.isDirectory()){ //若是目录,则递归该目录下的文件
listFiles(file1, sourceFile);
}else if (file1.isFile()){
sourceFile.add(file1); //若是文件,则保存
}
}
} }

使用到的maven依赖:

      <dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.8.1</version>
</dependency> <dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>0.7</version>
</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. 清理docker大日志文件

    1.进入容器文件的存放目录 ,并查看某一个容器的文件大小 [root@auto ~]# [root@auto ~]# cd /var/lib/docker/containers [root@auto ...

  2. c# 数据表DataTable给devexpress的gridControl提供数据源

    C# DataTable 详解 参考:https://www.cnblogs.com/Sandon/p/5175829.html http://blog.csdn.net/singgel/articl ...

  3. bat语法集【转】

    源文链接:http://www.cnblogs.com/jiangzhichao/archive/2012/02/15/2353004.html 1 echo 和 @@                 ...

  4. 归并排序 JavaScript 实现

    前文我们了解了快速排序算法的实现,本文我们来了解下另一种流行的排序算法-归并排序算法. 我们先来回顾下快排.快排的核心是找出一个基准元素,把数组中比该元素小的放到左边数组,比该元素大的放到右边数组,如 ...

  5. Kafka C++客户端库librdkafka笔记

    目录 目录 1 1. 前言 2 2. 缩略语 2 3. 配置和主题 3 3.1. 配置和主题结构 3 3.1.1. Conf 3 3.1.2. ConfImpl 3 3.1.3. Topic 3 3. ...

  6. Eclipse环境下如何配置tomcat,并且把项目部署到Tomcat服务器上

    打开Eclipse,单击“Window”菜单,选择下方的“Preferences”. 单击“Server”选项,选择下方的“Runtime Environments”.  点击“Add”添加Tomca ...

  7. (转)Eclipse开发Web项目

    1. 建立最简单的JSP和servlet http://wenku.baidu.com/link?url=bcf8iwB3E5_gjl46WfZAekQUWsps0-G3MAbbKz5totQcvmS ...

  8. MapGis如何实现WebGIS分布式大数据存储的

    作为解决方案厂商,MapGis是如何实现分布式大数据存储的呢? MapGIS在传统关系型空间数据库引擎MapGIS SDE的基础之上,针对地理大数据的特点,构建了MapGIS DataStore分布式 ...

  9. Using Spring.net in console application

    Download Spring.net in http://www.springframework.net/ Install Spring.NET.exe Create a console appli ...

  10. noip第6课资料