当前位置:才华咖 > 互联网计算机 > IT认证 > SUN认证 > 如何在java中解压zip和rar文件
手机版

如何在java中解压zip和rar文件

来源:才华咖 阅读:6.38K 次

为了方便广大的程序员朋友,下面讲一讲如何在java中实现对zip和rar文件的解压,一起和小编来看看吧!

如何在java中解压zip和rar文件

  一、解压rar文件。

由于WinRAR 是共享软件,并不是开源的,所以解压rar文件的前提是系统已经安装了winrar,比如本人的安装路径是:

C:Program FilesWinRAR

然后运用ess 的.相关知识来运行系统命令行来实现解压的。

winrar 命令行相关参数自己可以搜索下的网上资料很多

具体代码:

Java代码

**

* 解压rar文件(需要系统安装Winrar 软件)

* @author Michael sun

*/

public class UnRarFile {

/**

* 解压rar文件

*

* @param targetPath

* @param absolutePath

*/

public void unRarFile(String targetPath, String absolutePath) {

try {

// 系统安装winrar的路径

String cmd = "C:Program FilesWinRAR";

String unrarCmd = cmd + " x -r -p- -o+ " + absolutePath + " "

+ targetPath;

Runtime rt = untime();

Process pre = (unrarCmd);

InputStreamReader isr = new InputStreamReader(nputStream());

BufferedReader bf = new BufferedReader(isr);

String line = null;

while ((line = Line()) != null) {

line = ();

if (""ls(line)) {

continue;

}

tln(line);

}

e();

} catch (Exception e) {

tln("解压发生异常");

}

}

/**

* @param args

*/

public static void main(String[] args) {

String targetPath = "D:testunrar";

String rarFilePath = "D:test";

UnRarFile unrar = new UnRarFile();

rFile(targetPath, rarFilePath);

}

}

  二、解压zip文件

由于zip是免费的,所以在jdk里提供了相应的类对zip文件的实现:

.*,详细情况可以参考java API

Java代码

/**

* 解压zip文件

* @author Michael sun

*/

public class UnzipFile {

/**

* 解压zip文件

*

* @param targetPath

* @param zipFilePath

*/

public void unzipFile(String targetPath, String zipFilePath) {

try {

File zipFile = new File(zipFilePath);

InputStream is = new FileInputStream(zipFile);

ZipInputStream zis = new ZipInputStream(is);

ZipEntry entry = null;

tln("开始解压:" + ame() + "...");

while ((entry = extEntry()) != null) {

String zipPath = ame();

try {

if (rectory()) {

File zipFolder = new File(targetPath + rator

+ zipPath);

if (!ts()) {

rs();

}

} else {

File file = new File(targetPath + rator

+ zipPath);

if (!ts()) {

File pathDir = arentFile();

rs();

teNewFile();

}

FileOutputStream fos = new FileOutputStream(file);

int bread;

while ((bread = ()) != -1) {

e(bread);

}

e();

}

tln("成功解压:" + zipPath);

} catch (Exception e) {

tln("解压" + zipPath + "失败");

continue;

}

}

e();

e();

tln("解压结束");

} catch (Exception e) {

tStackTrace();

}

}

/**

* @param args

*/

public static void main(String[] args) {

String targetPath = "D:testunzip";

String zipFile = "D:test";

UnzipFile unzip = new UnzipFile();

pFile(targetPath, zipFile);

}

}

本文链接:https://www.caihuaka.com/itrz/sun/0jyqv7.html

Copyright © 2024. 才华咖 All right reserved. 浙ICP备20120231号-3

文字美图素材,版权属于原作者。部分文章内容由网友提供推送时因种种原因未能与原作者联系上,若涉及版权问题,敬请原作者联系我们,立即处理。