java批量解压文件夹下的所有压缩文件(.rar、.zip、.gz、.tar.gz)
// 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)的更多相关文章
- 【bat批处理】批量执行某个文件夹下的所有sql文件bat批处理
遍历文件夹下所有的sql文件,然后命令行执行 for /r "D:\yonyou\UBFV60\U9.VOB.Product.Other" %%a in (*.sql) do ( ...
- android XMl 解析神奇xstream 一: 解析android项目中 asset 文件夹 下的 aa.xml 文件
简介 XStream 是一个开源项目,一套简单实用的类库,用于序列化对象与 XML 对象之间的相互转换. 将 XML 文件内容解析为一个对象或将一个对象序列化为 XML 文件. 1.下载工具 xstr ...
- 读取同一文件夹下多个txt文件中的特定内容并做统计
读取同一文件夹下多个txt文件中的特定内容并做统计 有网友在问,C#读取同一文件夹下多个txt文件中的特定内容,并把各个文本的数据做统计. 昨晚Insus.NET抽上些少时间,来实现此问题,加强自身的 ...
- C#_IO操作_查询指定文件夹下的每个子文件夹占空间的大小
1.前言 磁盘内存用掉太多,想查那些文件夹占的内存比较大,再找出没有用的文件去删除. 2.代码 static void Main(string[] args) { while (true) { //指 ...
- 将文件夹下的所有csv文件存入数据库
# 股票的多因子分层回测代码实现 import os import pymysql # import datetime, time # from config import * database_ta ...
- linux 系统获得当前文件夹下存在的所有文件 scandir函数和struct dirent **namelist结构体[转]
linux 系统获得当前文件夹下存在的所有文件 scandir函数和struct dirent **namelist结构体 1.引用头文件#include<dirent.h> struct ...
- MATLAB读取一个文件夹下的多个子文件夹中的多个指定格式的文件
MATLAB需要读取一个文件夹下的多个子文件夹中的指定格式文件,这里以读取*.JPG格式的文件为例 1.首先确定包含多个子文件夹的总文件夹 maindir = 'C:\Temp Folder'; 2. ...
- MapReduce会自动忽略文件夹下的.开头的文件
MapReduce会自动忽略文件夹下的.开头的文件,跳过这些文件的处理.
- java解压多层目录中多个压缩文件和处理压缩文件中有内层目录的情况
代码: package com.xiaobai; import java.io.File; import java.io.FileOutputStream; import java.io.IOExce ...
随机推荐
- 再一道区间DP -- P4170 [CQOI2007]涂色
https://www.luogu.org/problemnew/show/P4170 一道简单的区间DP,注意读入 #include <bits/stdc++.h> #define up ...
- Mysql 数据库修改datadir和调整默认引擎要注意的问题
数据库更改 datadir 默认位置: 首先前面的基础操作我就不多说了,无非是复制mysqldata目录,然后修改 my.conf 配置文件 datadir 的 路径地址.然后重启mysql.这里可能 ...
- git安装项目步骤
1.git clone git@gitee(github).com:项目地址.git 2.cd 项目根目录 3.composer install 4.如果需要数据迁移,cmd中到项目根目录 php a ...
- vue的子传父
子组件传值给父组件,需要触发一个事件. 在这个事件里,使用this.$emit("父组件使用的名称","子组件的数据") 在父组件中引用的子组件,在子组件的标签 ...
- 第15章:MongoDB-聚合操作--聚合管道--$match
①$match 用于对文档集合进行筛选,里面可以使用所有常规的查询操作符. 通常会放置在管道最前面的位置,理由如下: 1:快速将不需要的文档过滤,减少后续操作的数据量 2:在投影和分组之前做筛选,查询 ...
- Ubuntu Server 命令行下的默认语言改为英语en_US.UTF-8
源文链接:http://tonychiu.blog.51cto.com/656605/393131 如果Ubuntu Server在安装过程中,选择的是中文(很多新手都会在安装时选择中文,便于上手), ...
- bzoj1212(trie+dp)
开始一看多个字符串就想ac自动机,结果发现不行.果然学傻了,,,,只要建个trie然后刷表dp就行了,复杂度最坏是O(字典中最长单词长度*文章长度)的.trie的空间换时间挺不错的. #include ...
- hdu 4704 Sum 【费马小定理】
题目 题意:将N拆分成1-n个数,问有多少种组成方法. 例如:N=4,将N拆分成1个数,结果就是4:将N拆分成2个数,结果就是3(即:1+3,2+2,3+1)--1+3和3+1这个算两个,则这个就是组 ...
- 怎样去写线程安全的代码(Java)
使用多线程就可能会存在线程安全的问题.很多 java 程序员对写多线程都很挣扎,或者仅仅理解那些是线程安全的代码,那些不是.这篇文章我并不是详述线程安全,详述同步机制的文章,相反我只是用一个简单的非线 ...
- Strom开发配置手册
一:Storm集群搭建 1.本次开发使用的是storm0.9.3 2.Storm0.9.3集群搭建: 1)storm集群角色包含集群主节点Nimbus:集群从节点Supervisor 2)集群安装:先 ...