java怎么解压压缩包(java实现对rar压缩包的解压)
一、导入相关的依赖包
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>7.4.0</version>
</dependency>
二、实现相应的工具类
import com.github.junrar.Archive;
import com.github.junrar.UnrarCallback;
import com.github.junrar.exception.RarException;
import com.github.junrar.rarfile.FileHeader;
import com.xxx.xxx.xxx.xxx.WkcrWord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
@Slf4j
public class UnRarFileUtil {
/**
* @param rarFileName rar file name
* @param rarFileName rar file name
* @param outFilePath output file path
* @param callback callback
* @throws Exception
*/
public static List<WkcrWord> unrar(File f,String rarFileName, String outFilePath, UnrarCallback callback) throws Exception {
//解压文件的对象
Archive archive = new Archive(f, callback);
if (archive == null) {
throw new FileNotFoundException(rarFileName " NOT FOUND!");
}
if (archive.isEncrypted()) {
throw new Exception(rarFileName " IS ENCRYPTED!");
}
List<WkcrWord> wkcrWords=new ArrayList<>();
List<FileHeader> files = archive.getFileHeaders();
for (FileHeader fh : files) {
if (fh.isEncrypted()) {
throw new Exception(rarFileName " IS ENCRYPTED!");
}
String fileName = fh.getFileName();
//获取标准的文件名
if(fileName.contains("\\")){
fileName=fileName.substring(fileName.lastIndexOf("\\") 1);
}
if (fileName != null && fileName.trim().length() > 0) {
String saveFileName = outFilePath fileName;
File saveFile = new File(saveFileName);
File parent = saveFile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
if (!saveFile.exists()) {
saveFile.createNewFile();
}
FileOutputStream fos=null;
if(saveFileName.contains(".doc")||saveFileName.contains(".docx")){
fos = new FileOutputStream(saveFile);
//获取返回的文件对象的集合
WkcrWord wkcrWord=new WkcrWord();
wkcrWord.setWordUrl(saveFileName);
wkcrWord.setName(fileName);
wkcrWords.add(wkcrWord);
}
try {
if(!StringUtils.isEmpty(fos)){
//解压文件输出到对应的目录下
archive.extractFile(fh, fos);
}
} catch (RarException e) {
throw new Exception("unrar error");
} finally {
try {
if(!StringUtils.isEmpty(fos)){
fos.flush();
fos.close();
}
} catch (Exception e) {
//自定义抛出异常
throw new RuntimeException("close Exception");
}
}
}
}
//-----
archive.close();
return wkcrWords;
}
}
三、方法的调用
List<WkcrWord> wkcrWords = UnRarFileUtil.unrar(f, modelNameAbsoulte, modelFilePath, new UnrarCallback() {
int currentProgress = -1;
@Override
public boolean isNextVolumeReady(Volume volume) {
return true;
}
@Override
public void volumeProgressChanged(long l, long l1) {
//可以进行解压的百分比计算
int progress = (int) ((double) l / l1 * 100);
if (currentProgress != progress) {
currentProgress = progress;
log.info(progress "%");
}
}
});
,
免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com