Java原生支持Zip格式的压缩,使用junrar可以对Rar5以下的进行解压,但是目前主流的都是RAR5,所以支持很困难。 找了很久终于找到了方法记录下来,使用该方法可以实现zip,rar5,7z等很多格式的解压功能,还能跨平台。
RandomAccessFile randomAccessFile = null;
IInArchive inArchive = null;
try {
// 判断目标目录是否存在,不存在则创建
File newdir = new File(targetFileDir);
if (false == newdir.exists()) {
newdir.mkdirs();
newdir = null;
}
randomAccessFile = new RandomAccessFile(inputFilePath, "r");
RandomAccessFileInStream t = new RandomAccessFileInStream(randomAccessFile);
if(inputFilePath.endsWith("rar")){
inArchive = SevenZip.openInArchive(ArchiveFormat.RAR5, t);
}
else if(inputFilePath.endsWith("7z")){
inArchive = SevenZip.openInArchive(ArchiveFormat.SEVEN_ZIP, t);
}
else{
inArchive = SevenZip.openInArchive(ArchiveFormat.ZIP, t);
}
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[]{0};
System.out.println("item.isFolder()==" + item.isFolder());
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
//写入指定文件
FileOutputStream fos;
try {
if (item.getPath().indexOf(File.separator) > 0) {
String path = targetFileDir + File.separator + item.getPath().substring(0, item.getPath().lastIndexOf(File.separator));
File folderExisting = new File(path);
if (!folderExisting.exists()){
new File(path).mkdirs();
}
}
fos = new FileOutputStream(targetFileDir + File.separator + item.getPath(), true);
fos.write(data);
fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s",hash[0], sizeArray[0], item.getPath()));
}
else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
e.printStackTrace();
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
DEMO完整示例: https://download.csdn.net/download/lainiao110/14032685