由于工作需要,写了一个小工具,利用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. Add `gem 'sqlite3'` to your Gemfile

    错误:Specified 'sqlite3' for database adapter, but the gem is not loaded. Add `gem 'sqlite3'` to your ...

  2. 搭建vue脚手架

    1.Node.js安装 1.1下载安装 在node.js 官网下载, 根据自己电脑系统安装,一直点下一步即可 1.2测试安装是否成功 Windows+R打开cmd窗口,输入node -v回车出现版本号 ...

  3. Java I/O (1) - 输入/输出流

    先说概念: Java API中,可以从其中读入一个字节序列的对象叫做输入流,可以向其中写入一个字节序列的对象叫做输出流.这些字节序列的来源地 和 目的地 可以文件.网络连接甚至内存块.抽象类Input ...

  4. ARM汇编指令格式

    一.ARM介绍 1) arm汇编中,程序下一步执行哪一条指令,是根据程序计数器(PC)的值来决定. 类比于8086的CS:IP的功能. 2) 8086属于CISC(复杂指令集),每条指令长度不等,ar ...

  5. angular中文文档的滚动条样式

    个人感觉angular中文文档的滚动条样式非常棒,于是乎就扒了下来 https://www.angular.cn/ body::-webkit-scrollbar { /* 定义了滚动条整体的样式 * ...

  6. Kubernetes 1.3.1 快速单机部署

    Kubernetes发展到今天, 在官网上已经有非常多的成熟部署方案, 但是由于墙的原因, 最简单的MiniKube都无法进行, 参考了以下两篇文章后, 终于安装成功. k8s-1.13版本测试环境搭 ...

  7. tomcat中如何禁止列目录下的文件

    tomcat中如何禁止列目录下的文件在{tomcat_home}/conf/web.xml中,把listings参数设置成false即可,如下: <servlet> <servlet ...

  8. idea实现热部署并且开启自动编译

    [注]本文转自https://blog.csdn.net/z15732621582/article/details/79439359博文,如有冒犯,请联系博主: 问题描述: 最近在调试代码并进行本地测 ...

  9. 摹客iDoc的PS插件全新改版!—— 智能检测不对应的设计稿

    一.简洁美观——iDoc的PS插件全新界面 iDoc对PS插件的界面进行了全新设计,无论是登录.上传.还是设置界面,都变得更精致.简洁美观,功能分布也非常明确,是一款轻巧且实用的小插件. 二.同步上传 ...

  10. Finance财务软件(引入业务系统凭证专题)

    我们通过自定义存储过程从业务系统引入凭证 我们需要以下适配 1.设置业务系统数据库链接 2.在自定义模板中设置存储过程名称及入参,这里的功能键值必须为_InterfaceExec,保留字段作为存储过程 ...