public void UnRar(String RarPath, String targetPath) throws Exception {
Archive archive = null;
FileOutputStream outputStream = null;
archive = new Archive(new File(RarPath));
FileHeader f = archive.nextFileHeader();
while (f != null) {
// 当前为文件夹,下移
if (f.isDirectory()) {
f = archive.nextFileHeader();
continue;
}
// 判断编码,解决中文乱码的问题
String localpath = f.isUnicode() ? f.getFileNameW() : f
.getFileNameString();
// 得到的localpath分隔符为"\",转为为"/"
localpath = targetPath
+ localpath.replaceAll("\\\\", File.separator);
int end = localpath.lastIndexOf(File.separator);
String dir = localpath;
if (end != -1) {
dir = localpath.substring(0, end);
}
// 需要创建文件夹
File file = new File(dir);
if (!file.exists()) {
file.mkdir();
}
outputStream = new FileOutputStream(localpath);
// archive自己的生成文件的方法
archive.extractFile(f, outputStream);
f = archive.nextFileHeader();
}
outputStream.close();
archive.close();
}
private void UnZip(String zipPath, String targetPath) throws Exception {
File file = new File(zipPath);
if (!file.isFile()) {
throw new FileNotFoundException();
}
// 实例化ZipFile对象
ZipFile zipFile = new ZipFile(file);
// 根据文件的编码创建,解决中文乱码的问题,getEncoding()有可能为null,就默认编码
zipFile = new ZipFile(file, zipFile.getEncoding());
// 获取ZipFile中的条目
Enumeration<ZipEntry> files = zipFile.getEntries();
// 迭代中的每一个条目
ZipEntry entry = null;
// 解压后的文件
File outFile = null;
// 读取压缩文件的输入流
BufferedInputStream bin = null;
// 写入解压后文件的输出流
BufferedOutputStream bout = null;
while (files.hasMoreElements()) {
// 获取解压条目
entry = files.nextElement();
// 实例化解压后文件对象
String path_temp = null;
path_temp = targetPath + entry.getName();
outFile = new File(path_temp);
if (entry.getName().endsWith(File.separator)) {
if (!outFile.exists()) {
outFile.mkdirs();
}
continue;
}
// 创建目录
if (!outFile.getParentFile().exists()) {
outFile.getParentFile().mkdirs();
}
if (outFile.exists()) {
outFile.delete();
}
// 获取读取条目的输入流
bin = new BufferedInputStream(zipFile.getInputStream(entry));
// 获取解压后文件的输出流
bout = new BufferedOutputStream(new FileOutputStream(outFile));
// 读取条目,并写入解压后文件
byte[] buffer = new byte[1024];
int readCount = -1;
while ((readCount = bin.read(buffer)) != -1) {
bout.write(buffer, 0, readCount);
}
bout.flush();
bin.close();
bout.close();
buffer = null;
}
}