<!--zip 工具-->
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.9.7</version>
</dependency>
<!--rar 工具-->
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>6.0.1</version>
</dependency>
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import java.io.*;
import java.util.Enumeration;
/**
* 解压缩工具类
*
* @author dgb8901
*/
public class ZipAndRarTools {
/**
* 解压rar文件
*
* @param sourcePath 解压的rar文件路径
* @param destPath 解压到的文件目录
* @throws Exception
*/
public static void unRar(String sourcePath, String destPath) throws Exception {
File sourceRar = new File(sourcePath);
File destDir = new File(destPath);
Archive archive = null;
FileOutputStream fos = null;
try {
archive = new Archive(new FileInputStream(sourceRar));
FileHeader fh = archive.nextFileHeader();
int count = 0;
File destFileName = null;
while (fh != null) {
++count;
System.out.println((count) + ") " + fh.getFileNameString());
String compressFileName = fh.getFileNameString().trim();
destFileName = new File(destDir.getAbsolutePath() + "/" + 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) {
e.printStackTrace();
throw e;
} finally {
if (fos != null) {
fos.close();
fos = null;
}
if (archive != null) {
archive.close();
archive = null;
}
}
}
/**
* 解压Zip文件
*
* @param zipPath 解压缩的文件位置
* @param destPath 解压到某个路径
*/
public static void unZip(String zipPath, String destPath) {
String descFileNames = destPath;
if (!descFileNames.endsWith(File.separator)) {
descFileNames = descFileNames + File.separator;
}
try {
ZipFile zipFile = new ZipFile(zipPath);
ZipEntry entry = null;
String entryName = null;
String descFileDir = null;
byte[] buf = new byte[4096];
int readByte = 0;
Enumeration<ZipEntry> enums = zipFile.getEntries();
while (enums.hasMoreElements()) {
entry = enums.nextElement();
entryName = entry.getName();
descFileDir = descFileNames + entryName;
if (entry.isDirectory()) {
new File(descFileDir).mkdirs();
continue;
} else {
new File(descFileDir).getParentFile().mkdirs();
}
File file = new File(descFileDir);
OutputStream os = new FileOutputStream(file);
InputStream is = zipFile.getInputStream(entry);
while ((readByte = is.read(buf)) != -1) {
os.write(buf, 0, readByte);
}
os.close();
is.close();
}
zipFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
很遗憾的说,推酷将在这个月底关闭。人生海海,几度秋凉,感谢那些有你的时光。
原文 https://www.itwork.club/2020/07/23/zip-rar/