业务需求:通过Java程序,不使用命令解压zip和rar压缩文件(7z可以解压rar)
读取异常处理
/**
* 系统异常类
* @author sgq
*/
public class ReadZipException extends Exception {
private static final long serialVersionUID = 1L;
public ReadZipException(String message) {
super(message);
}
public ReadZipException(String message, Throwable ex) {
super(message, ex);
}
public ReadZipException(Throwable ex) {
super(ex);
}
}
所需依赖
<!-- https://mvnrepository.com/artifact/ant/ant --> ===》可以获取最新依赖
<!--zip-->
<dependency>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
<version>1.6.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.junrar/junrar --> ===》可以获取最新依赖
<!-- 解压rar -->
<!--<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>4.0.0</version>
</dependency>-->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>java-unrar</artifactId>
<version>1.7.0-8</version>
</dependency>
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>0.7</version>
</dependency>
<!--7z rar使用7z依赖-->
<dependency>
<groupId>net.sf.sevenzipjbinding</groupId>
<artifactId>sevenzipjbinding</artifactId>
<version>16.02-2.01</version>
</dependency>
<--rar必须引入,否则会出现空指针-->
<dependency>
<groupId>net.sf.sevenzipjbinding</groupId>
<artifactId>sevenzipjbinding-all-platforms</artifactId>
<version>16.02-2.01</version>
</dependency>
<--io流-->
<dependency>
<artifactId>commons-io</artifactId>
<groupId>commons-io</groupId>
<version>2.0.1</version>
</dependency>
解压zip
/**
* zip解压
* @throws RuntimeException 解压失败会抛出运行时异常
* path 压缩文件路径
* destDirPath 文件存放路径
*/
public static void unZipFiles(String path, String destDirPath) throws Exception {
File srcFile = new File(path);
long start = System.currentTimeMillis();
// 判断源文件是否存在
if (!srcFile.exists()) {
throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
}
//获取压缩包文件名--解压后的目标文件夹
//destDirPath = destDirPath+name;
// 开始解压
ZipFile zipFile = null;
File targetFile = null;
try {
zipFile = new ZipFile(srcFile, Charset.forName("GBK"));
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
System.out.println("解压" + entry.getName());
// 如果是文件夹,就创建个文件夹
if (entry.isDirectory()) {
String dirPath = destDirPath + File.separator + entry.getName();
File dir = new File(dirPath);
dir.mkdirs();
} else {
// 如果是文件,就先创建一个文件,然后用io流把内容copy过去
targetFile = new File(destDirPath + File.separator + entry.getName());
// 保证这个文件的父文件夹必须要存在
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
// 将压缩文件内容写入到这个文件中
InputStream is = zipFile.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(targetFile);
int len;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
// 关流顺序,先打开的后关闭
fos.close();
is.close();
}
}
long end = System.currentTimeMillis();
System.out.println("解压完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("unzip error from ZipUtils", e);
} finally {
if (zipFile != null) {
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
解压
API文档:点击(点击类可以查看文档)
参考文章:点击
/**
* 解压rar格式
* @param filePath 压缩文件路径
* @param destDirPath 保存路径
* @throws Exception
*/
public static void unrar(String filePath, String destDirPath) throws Exception {
File file =new File(filePath);
if (!file.exists()) {
throw new RuntimeException(file.getPath() + "所指文件不存在");
}
// 可以指定解压的位置
//int pos = file.getName().lastIndexOf(".");//从后查询后缀
//解压位置
// String descDir = destDirPath + File.separator+ file.getName().substring(0, pos)+File.separator; //截取到后缀,作为文件夹
//开始解压rar
ReadZipFileUtils.unRarFile(file.getAbsolutePath(), destDirPath);
}
调用下面方法:缺点只可以为rar压缩文件,zip压缩文件无法打开
//解压rar所用到的方法
public static void unRarFile(String srcRarPath, String dstDirectoryPath) {
RandomAccessFile randomAccessFile = null;
IInArchive inArchive = null;
File file = new File(dstDirectoryPath);
if (!file.exists()) {
file.mkdirs();
}
try {
randomAccessFile = new RandomAccessFile(new File(srcRarPath), "r");
inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
//创建文件大小为0的数据
for (int idx = 0; idx < inArchive.getNumberOfItems(); idx++) {
String property = (String)inArchive.getProperty(idx, PropID.PATH);//文件名称
boolean b1 = property.toLowerCase().endsWith(".rar");
if (!b1) { //先创建非压缩包内容
File tarFile = new File(file + File.separator + property);
if (!tarFile.isDirectory()){
if (!tarFile.getParentFile().exists()) { //判断父级
tarFile.getParentFile().mkdirs();
}
if (!tarFile.exists()) {
if (!(boolean) ((property.contains(".")))) { //判断最后一级为文件夹
tarFile.mkdir();
}else {tarFile.createNewFile();}
}}
else {
tarFile.mkdir();
}
}
}
for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
File tarFile = new File(file + File.separator + item.getPath());
//防止包含空文件夹
item.extractSlow(new ISequentialOutStream() { //开始解压
public int write(byte[] data) throws SevenZipException {
FileOutputStream fos = null;
try {
if (!tarFile.getParentFile().exists()) { //判断父级
tarFile.getParentFile().mkdirs();
}
tarFile.createNewFile();
fos = new FileOutputStream(tarFile.getAbsolutePath());
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data.length;
}
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
e.printStackTrace();
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}