我正在寻找一种使用 Java 解压缩 .rar
文件的方法,无论我在哪里搜索,我都以相同的工具结束 - JavaUnRar
。我一直在研究解压缩 .rar
文件,但我似乎发现这样做的所有方法都非常长且笨拙,就像在 这个例子 中一样
I am currently able to extract .tar
, .tar.gz
, .zip
and .jar
files in 20 lines of code or less so there must be a提取 .rar
文件的更简单方法,有人知道吗?
如果它对任何人有帮助,这就是我用来提取 .zip
和 .jar
文件的代码,它适用于这两个文件
public void getZipFiles(String zipFile, String destFolder) throws IOException {
BufferedOutputStream dest = null;
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(
new FileInputStream(zipFile)));
ZipEntry entry;
while (( entry = zis.getNextEntry() ) != null) {
System.out.println( "Extracting: " + entry.getName() );
int count;
byte data[] = new byte[BUFFER];
if (entry.isDirectory()) {
new File( destFolder + "/" + entry.getName() ).mkdirs();
continue;
} else {
int di = entry.getName().lastIndexOf( '/' );
if (di != -1) {
new File( destFolder + "/" + entry.getName()
.substring( 0, di ) ).mkdirs();
}
}
FileOutputStream fos = new FileOutputStream( destFolder + "/"
+ entry.getName() );
dest = new BufferedOutputStream( fos );
while (( count = zis.read( data ) ) != -1)
dest.write( data, 0, count );
dest.flush();
dest.close();
}
}
原文由 flexinIT 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以提取
.gz
,.zip
,.jar
文件,因为它们使用了 Java SDK 中内置的压缩算法。RAR 格式的情况有点不同。 RAR 是 专有 的存档文件格式。 RAR 许可证 不允许将其包含到 Java SDK 等软件开发工具中。
解压缩文件的最佳方法是使用 3rd 方库,例如 junrar 。
您可以在 SO question RAR archives with java 中找到对其他 Java RAR 库的一些引用。还有一个问题 How to compress text file to rar format using java program 解释了更多不同的解决方法(例如使用
Runtime
)。