最近,手上维护着一个几年前的系统,技术是用的JSP+Strust2,系统提供了rar和zip两种压缩格式的解压功能,后台是用java实现的

1、解压rar格式,采用的是java-unrar-0.3.jar

2、解压zip格式,采用的是commons-compress-1.4.1.jar

但最近根据用户反馈的问题,发现系统存在两个关于压缩文件解压的问题:

1、有些压缩文件解压之后出现中文乱码;

2、有些压缩文件根本不能解压

为了弥补上述两个问题,在之前代码的基础上打了一些补丁,来解决zip压缩包乱码的问题,思路大概是:

1、采用GBK编码解压

2、递归遍历解压的文件名是否存在中文乱码,这用到了网上很常用的中文检测正则表示式,[\u4e00-\u9fa5]+

3、如果存在中文乱码,则采用UTF-8编码解压

替换后,还是有人反映乱码问题,烦~~~

第二个问题报错如下(出现在有些rar格式解压时):

WARNING: exception in archive constructor maybe file is encrypted or currupt
de.innosystec.unrar.exception.RarException: badRarArchive
at de.innosystec.unrar.Archive.readHeaders(Archive.java:238)
at de.innosystec.unrar.Archive.setFile(Archive.java:122)
at de.innosystec.unrar.Archive.(Archive.java:106)
at de.innosystec.unrar.Archive.(Archive.java:96)
at com.reverse.zipFile.CopyOfZipFileUtil.unrar(CopyOfZipFileUtil.java:242)
at com.reverse.zipFile.CopyOfZipFileUtil.main(CopyOfZipFileUtil.java:303)

借助百度、谷歌找资料发现:

1、java解压文件有两种方式,一是自己写代码,二是调用压缩软件CMD执行

2、第二个错误是由于WinRAR5之后,在rar格式的基础上,推出了另一种rar,叫RAR5,而java-unrar解析不了这种格式

查看rar格式属性可以通过右键 —> 属性查看,如图


因此需要舍弃代码解压的方式,改为CMD调用的方式,虽然压缩软件有很多,但从网上能找到执行命令的,也就WinRAR了,所以我们采用WinRAR5之后的版本解决,5之前的版本肯定是不行的了

使用cmd方式效果如何呢?既能解决中文乱码问题,又能解压RAR5压缩文件,而且代码量还更少了,支持的格式也更多了。

附上CMD方式调用代码:

/*** 采用命令行方式解压文件
*@paramzipFile 压缩文件
*@paramdestDir 解压结果路径
*@return
*/
public static booleanrealExtract(File zipFile, String destDir) {//解决路径中存在/..格式的路径问题
destDir = newFile(destDir).getAbsoluteFile().getAbsolutePath();while(destDir.contains("..")) {
String[] sepList= destDir.split("\\\\");
destDir= "";for (int i = 0; i < sepList.length; i++) {if(!"..".equals(sepList[i]) && i < sepList.length -1 && "..".equals(sepList[i+1])) {
i++;
}else{
destDir+= sepList[i] +File.separator;
}
}
}//获取WinRAR.exe的路径,放在java web工程下的WebRoot路径下
String classPath = "";try{
classPath= Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath();
}catch(URISyntaxException e1) {
e1.printStackTrace();
}//兼容main方法执行和javaweb下执行
String winrarPath = (classPath.indexOf("WEB-INF") > -1 ? classPath.substring(0, classPath.indexOf("WEB-INF")) :
classPath.substring(0, classPath.indexOf("classes"))) + "/WinRAR/WinRAR.exe";
winrarPath= newFile(winrarPath).getAbsoluteFile().getAbsolutePath();
System.out.println(winrarPath);boolean bool = false;if (!zipFile.exists()) {return false;
}//开始调用命令行解压,参数-o+是表示覆盖的意思
String cmd = winrarPath + " X -o+ " + zipFile + " " +destDir;
System.out.println(cmd);try{
Process proc=Runtime.getRuntime().exec(cmd);if (proc.waitFor() != 0) {if (proc.exitValue() == 0) {
bool= false;
}
}else{
bool= true;
}
}catch(Exception e) {
e.printStackTrace();
}
System.out.println("解压" + (bool ? "成功" : "失败"));returnbool;
}