java解压rar有的用cmd命令行调用winrar.exe,这其实是一个很不好的方法,主要理由如下:
1:会出现解压的页面
2:如果压缩包有错误,会弹出解压警告框。
其实有一个可以实现解压,但是网上很多的用法都是不对的,我这里参考了一些资料写了一个。
/**
* 根据原始rar路径,解压到指定文件夹下.
* @param srcRarPath 原始rar路径
* @param dstDirectoryPath 解压到的文件夹
*/
public static void unRarFile(String srcRarPath, String dstDirectoryPath) {
if (!srcRarPath.toLowerCase().endsWith(".rar")) {
System.out.println("非rar文件!");
return;
}
File dstDiretory = new File(dstDirectoryPath);
if (!dstDiretory.exists()) { //目标目录不存在时,创建该文件夹
dstDiretory.mkdirs();
}
Archive a = null;
try {
a = new Archive(new File(srcRarPath));
if (a != null) {
a.getMainHeader().print(); //打印文件信息.
FileHeader fh = a.nextFileHeader();
while (fh != null) {
if (fh.isDirectory()) { //文件夹
File fol = new File(dstDirectoryPath + File.separator + fh.getFileNameString());
fol.mkdirs();
} else { //文件
File out = new File(dstDirectoryPath + File.separator + fh.getFileNameString().trim());
System.out.println(out.getAbsolutePath());
try {//之所以这么写try,是因为万一这里面有了异常,不影响继续解压.
if (!out.exists()) {
if (!out.getParentFile().exists()) {//相对路径可能多级,可能需要创建父目录.
out.getParentFile().mkdirs();
}
out.createNewFile();
}
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
os.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
fh = a.nextFileHeader();
}
a.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
有可能在实际应用中会遇到java.lang.OutOfMemoryError: Java heap space,这主要是因为解压比较大的rar文件时,内存消耗过大所致。解决办法:
1、如果是在eclipse或者myeclipse中用:只需在Run - Open Run Dailog中坐如下配置(1000m根据自己机器情况调整)
2、如果作为应用程序调用 只需 java -Xms1000m 启动类名称
在实际应用中还可能出现rar文件可以有winrar打开,但是解压总报错在 a = new Archive(new File(srcRarPath)); 如果这样尝试用zip格式解压即可。
如果觉得《java解压rar 解压rar报错》对你有帮助,请点赞、收藏,并留下你的观点哦!