/**
* @Title: unZipFile
* @Description: 解压ZIP文件
* @author LuRh
* @param @param zipFile
* @param @param descDir
* @param @return
* @param @throws IOException
* @return boolean
* @throws
*/
@SuppressWarnings("rawtypes")
public static boolean unZipFile(String filePath, String extractToPath) {
try {
File zipFile = new File(filePath);
File extractPath = new File(extractToPath);
if (!extractPath.exists()) {
extractPath.mkdirs();
}
ZipFile zip = new ZipFile(zipFile, "GBK");
for (Enumeration entries = zip.getEntries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (extractToPath + zipEntryName).replaceAll("\\*", "/");
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!file.exists()) {
file.mkdirs();
}
if (new File(outPath).isDirectory()) {
continue;
}
if (in != null) {
OutputStream out = new FileOutputStream(outPath);
byte[] buf = new byte[2048];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
} catch (IOException e) {
return false;
}
return true;
}
/**
* @Title: unRARFile
* @Description: 解压RAR文件
* @author LuRh
* @param @param sourceRar
* @param @param destDir
* @param @return
* @param @throws Exception
* @return boolean
* @throws
*/
public static boolean unRARFile(String filePath, String extractToPath) {
Archive archive = null;
FileOutputStream fileOutputStream = null;
try {
archive = new Archive(new File(filePath));
FileHeader fileHeader = archive.nextFileHeader();
while (fileHeader != null) {
if (!fileHeader.isDirectory()) {
String compressFileName = "";
String destFileName = "";
String destDirName = "";
if (fileHeader.isUnicode()) {
compressFileName = fileHeader.getFileNameW().trim();
} else {
compressFileName = fileHeader.getFileNameString().trim();
}
// 非windows系统
if (File.separator.equals("/")) {
destFileName = extractToPath + compressFileName.replaceAll("\\\\", "/");
destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));
// windows系统
} else {
destFileName = extractToPath + compressFileName.replaceAll("/", "\\\\");
destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));
}
File dir = new File(destDirName);
if (!dir.exists() || !dir.isDirectory()) {
dir.mkdirs();
}
fileOutputStream = new FileOutputStream(new File(destFileName));
archive.extractFile(fileHeader, fileOutputStream);
fileOutputStream.close();
fileOutputStream = null;
}
fileHeader = archive.nextFileHeader();
}
archive.close();
archive = null;
} catch (Exception e) {
return false;
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
fileOutputStream = null;
} catch (Exception e) {
e.printStackTrace();
}
}
if (archive != null) {
try {
archive.close();
archive = null;
} catch (Exception e) {
return false;
}
}
}
return true;
}
JAVA解压RAR和ZIP
最新推荐文章于 2024-03-17 09:39:46 发布