由于工作需要,写了一个小工具,利用java来解压文件然后对文件进行重命名

主要针对三种格式,分别是zip,rar,7z,经过我的多次实践我发现网上的类库并不能解压最新的压缩格式

对于zip格式:

maven依赖

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.9</version>
</dependency>

代码如下:

  private static Boolean unzip(String fileName, String unZipPath, String rename) throws Exception {
boolean flag = false;
File zipFile = new File(fileName); ZipFile zip = null;
try {
//指定编码,否则压缩包里面不能有中文目录
zip = new ZipFile(zipFile, Charset.forName("GBK")); for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = null;
try {
entry = (ZipEntry) entries.nextElement();
} catch (Exception e) {
return flag;
} String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String[] split = rename.split("\n");
for (int i = 0; i < split.length; i++) {
zipEntryName = zipEntryName.replace(split[i], " ");//这里可以替换原来的名字
}
String outPath = (unZipPath + zipEntryName).replace("/", File.separator); //解压重命名 //判断路径是否存在,不存在则创建文件路径
File outfilePath = new File(outPath.substring(0, outPath.lastIndexOf(File.separator)));
if (!outfilePath.exists()) {
outfilePath.mkdirs();
}
//判断文件全路径是否为文件夹
if (new File(outPath).isDirectory()) {
continue;
}
//保存文件路径信息
//urlList.add(outPath); OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[2048];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
in.close();
out.close();
}
flag = true;
//必须关闭,否则无法删除该zip文件
zip.close();
} catch (IOException e) {
flag = false;
} return flag; }

对于zip的文件大部分可以解压但是我发现有些的中文编码得是UTF-8才能解压,因此设置成GBK 不是绝对的

7z格式的就和网上大部分的代码类似

maven依赖同上的

 public static Boolean apache7ZDecomp(String orgPath, String tarpath, String rename) {
boolean flag = false;
try {
SevenZFile sevenZFile = new SevenZFile(new File(orgPath));
SevenZArchiveEntry entry = sevenZFile.getNextEntry();
while (entry != null) { // System.out.println(entry.getName());
if (entry.isDirectory()) { new File(tarpath + entry.getName()).mkdirs();
entry = sevenZFile.getNextEntry();
continue;
}
String entryName = entry.getName();
String[] split = rename.split("\n");
for (int i = 0; i < split.length; i++) {
entryName = entryName.replace(split[i], "");//这里是对原来的名字进行替换,也可以写你想要换的名字
}
String tarpathFileName = (tarpath + entryName).replace("/", File.separator);
File fileDir = new File(tarpath);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
FileOutputStream out = new FileOutputStream(tarpathFileName);
byte[] content = new byte[(int) entry.getSize()];
sevenZFile.read(content, 0, content.length);
out.write(content);
out.close();
entry = sevenZFile.getNextEntry();
flag = true;
}
sevenZFile.close();
} catch (FileNotFoundException e) {
return flag;
} catch (IOException e) {
return flag;
}
return flag;
}

还有一种是用这个类库:                                                                                    

<dependency>
<groupId>net.sf.sevenzipjbinding</groupId>
<artifactId>sevenzipjbinding</artifactId>
<version>9.20-2.00beta</version>
</dependency> <dependency>
<groupId>net.sf.sevenzipjbinding</groupId>
<artifactId>sevenzipjbinding-all-platforms</artifactId>
<version>9.20-2.00beta</version>
</dependency> 1 public static void un7ZipFile(String filepath, String targetFilePath, String rename) {

final File file = new File(targetFilePath);
if (!file.exists()) {
file.mkdirs();
}
RandomAccessFile randomAccessFile = null;
IInArchive inArchive = null; try {
randomAccessFile = new RandomAccessFile(filepath, "r");
inArchive = SevenZip.openInArchive(null,
new RandomAccessFileInStream(randomAccessFile)); ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface(); for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[]{0};
if (!item.isFolder()) {
ExtractOperationResult result; final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException { FileOutputStream fos = null;
try {
String fileName = item.getPath();
String[] split = rename.split("\r\n");
for (int i = 0; i < split.length; i++) {
fileName = fileName.replace(split[i], "");
} File tarFile = new File(file + File.separator + fileName); if (!tarFile.getParentFile().exists()) {
tarFile.getParentFile().mkdirs();
}
tarFile.createNewFile();
fos = new FileOutputStream(tarFile.getAbsolutePath());
fos.write(data);
fos.close(); } catch (FileNotFoundException e) { } catch (IOException e) { } hash[0] ^= Arrays.hashCode(data);
sizeArray[0] += data.length;
return data.length;
}
});
if (result == ExtractOperationResult.OK) {
// System.out.println(String.format("%9X | %10s | %s", //
// hash[0], sizeArray[0], item.getPath()));
} else {
// System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
e.printStackTrace();
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
  
  <groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>3.0.0</version>
</dependency>
 public static boolean unrar(String rarFileName, String outFilePath, String rename) throws Exception {

        try {
Archive archive = new Archive(new File(rarFileName), new UnrarProcessMonitor(rarFileName));
if (archive == null) {
throw new FileNotFoundException(rarFileName + " NOT FOUND!");
}
if (archive.isEncrypted()) {
throw new Exception(rarFileName + " IS ENCRYPTED!");
}
List<FileHeader> files = archive.getFileHeaders();
for (FileHeader fh : files) {
if (fh.isEncrypted()) {
throw new Exception(rarFileName + " IS ENCRYPTED!");
}
String fileName = fh.getFileNameW().isEmpty() ? fh.getFileNameString() : fh.getFileNameW();
String[] split = rename.split("\n");
for (int i = 0; i < split.length; i++) {
fileName = fileName.replace(split[i], ""); //解压重命名
}
if (fileName != null && fileName.trim().length() > 0) {
String saveFileName = outFilePath + File.separator + fileName;
File saveFile = new File(saveFileName);
File parent = saveFile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
if (!saveFile.exists()) {
saveFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(saveFile);
try {
archive.extractFile(fh, fos);
fos.flush();
fos.close();
} catch (RarException e) { } finally {
}
}
}
return true;
} catch (Exception e) {
System.out.println("failed.");
return false;
}
}

//对解压rar文件进度的监控

public class UnrarProcessMonitor implements UnrarCallback {
private String fileName; public UnrarProcessMonitor(String fileName) {
this.fileName = fileName;
} /**
* 返回false的话,对于某些分包的rar是没办法解压正确的
* */
@Override
public boolean isNextVolumeReady(Volume volume) {
try {
fileName = ((FileVolume) volume).getFile().getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
} @Override
public void volumeProgressChanged(long l, long l1) {
//输出进度
System.out.println("Unrar "+fileName+" rate: "+(double)l/l1*100+"%");
} } 最后就是如果三种方法都无法解压我们就应该调用cmd来用WinRar进行解压
public static boolean unfile(String zipFile,String outFilePath,int mode){
boolean flag=false;
try{
File file = new File(zipFile);
String fileName = file.getName();
if(mode == 1)
{
outFilePath += File.separator; //文件当前路径下
}else{
outFilePath += File.separator+fileName.substring(0,fileName.length()-4)+File.separator;
}
File tmpFileDir = new File(outFilePath);
tmpFileDir.mkdirs(); String unrarCmd = "C:\\Program Files\\WinRAR\\WinRar e ";
unrarCmd += zipFile + " " + outFilePath;
try {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(unrarCmd); InputStream inputStream=p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
while (br.readLine()!=null){
}
p.waitFor();
br.close();
inputStream.close();
p.getErrorStream().close();
p.getOutputStream().close();
flag=true;
} catch (Exception e) {
System.out.println(e.getMessage());
} }catch(Exception e){
}
return flag;
}

以上就是解压的方法,总体坐下来感觉还是调用cmd最简单直接,然后压缩的话基本上大部分都可以压缩,就不写上压缩的代码了

    

利用java解压,并重命名的更多相关文章

  1. 关于Java解压文件的一些坑及经验分享(MALFORMED异常)

    文章也已经同步到我的csdn博客: http://blog.csdn.net/u012881584/article/details/72615481 关于Java解压文件的一些坑及经验分享 就在本周, ...

  2. Java解压和压缩带密码的zip或rar文件(下载压缩文件中的选中文件、向压缩文件中新增、删除文件)

    JAVA 实现在线浏览管理zip和rar的工具类 (有密码及无密码的)以及下载压缩文件中的选中文件(向压缩文件中新增.删除文件) 这是之前的版本 JAVA 解压压缩包中指定文件或实现压缩文件的预览及下 ...

  3. JAVA解压.Z及.ZIP文件

    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-compress --> <dependency ...

  4. java利用zip解压slpk文件

    public static void main(String[] args) { File file = new File("C:\\Users\\Administrator\\Deskto ...

  5. 【java】 java 解压tar.gz读取内容

    package com.xwolf.stat.util; import com.alibaba.druid.util.StringUtils; import com.alibaba.fastjson. ...

  6. Java解压上传zip或rar文件,并解压遍历文件中的html的路径

    1.本文只提供了一个功能的代码 public String addFreeMarker() throws Exception { HttpSession session = request.getSe ...

  7. java 解压 zip 包并删除

    需求是这样的,  在服务器上有 运营上传的zip 包,内容是用户的照片,我需要做的是 获取这些照片上传,并保存到 数据库. 这里面的 上传照片,保存数据库都不难,主要问题是解压zip包,和删除zip ...

  8. Java 解压zip压缩包

    因为最近项目需要批量上传文件,而这里的批量就是将文件压缩在了一个zip包里,然后读取文件进行解析文件里的内容. 因此需要先对上传的zip包进行解压.以下直接提供代码供参考: 1.第一个方法是用于解压z ...

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

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

随机推荐

  1. java实现将包含多个<REC>的文件拆成若干只包含一个<REC>的文件

    遍历文件夹里的文件,将包含多个<REC>的文件拆成若干只包含一个<REC>的文件 package com.prepub; import java.io.BufferedRead ...

  2. rsync配置安装

    rsync安装 1.将rsync包解压,包链接: https://pan.baidu.com/s/1jHPosXC 密码: maay 2.进入rsync安装包运行命令: ./configure --p ...

  3. 通信导论-IP数据网络基础(3)

    ICMP(IP辅助协议)--网际控制报文协议 ICMP报文种类:ICMP差错报文(终点不可达.时间超过等5种)和ICMP询问报文(回送请求和回答请求.时间戳请求和回答报文2种) ICMP是一种集差错报 ...

  4. mac相关功能

    打开和关闭索引功能 打开:sudo mdutil -a -i on 关闭:sudo mdutil -a -i off 关闭后则无法搜

  5. Python基础-python流程控制之顺序结构和分支结构(五)

    流程控制 流程:计算机执行代码的顺序,就是流程 流程控制:对计算机代码执行顺序的控制,就是流程控制 流程分类:顺序结构.选择结构(分支结构).循环结构 顺序结构 一种代码自上而下执行的结构,是pyth ...

  6. SQL Server数据库中的系统数据库?

    SQL Server的系统数据库分为:master,model,msdb和tempdb 1.Master数据库 Master数据库记录SQL Server系统的所有系统级别信息(表sysobjects ...

  7. 20164319 刘蕴哲 Exp2 后门原理与实践

    [后门概念] 后门就是不经过正常认证流程而访问系统的通道. 特指潜伏于操作系统中专门做后门的一个程序,而“坏人”可以连接这个程序远程执行各种指令. (概念和木马有重叠) [学习内容] 使用nc实现wi ...

  8. tiny4412 --Uboot移植(4) 串口

    开发环境:win10 64位 + VMware12 + Ubuntu14.04 32位 工具链:linaro提供的gcc-linaro-6.1.1-2016.08-x86_64_arm-linux-g ...

  9. BFC是什么及能用它能做什么

    最近较为频繁的碰到了一个新的名词:BFc,每次都可以在相关的技术博客里面看到对其的简单介绍,刚开始以为自己懂了,但实际上没懂,今天就来搞清楚它到底是什么,以及我们能用他做什么? BFC:全名为 Blo ...

  10. nova-api nova-compute 启动服务的时候有的没有加配置文件有的加了

    nova/nova/cmd/api.pyfrom nova import config def main(): config.parse_args(sys.argv) logging.setup(CO ...