java解压Zip、Rar文件

一、解压zip文件
由于zip是免费的,所以在jdk里提供了相应的类对zip文件的实现:
java.util.zip.*,详细情况可以参考java API
    /** 
* 解压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;
System.out.println("开始解压:" + zipFile.getName() + "...");
while ((entry = zis.getNextEntry()) != null) {
String zipPath = entry.getName();
try {

if (entry.isDirectory()) {
File zipFolder = new File(targetPath + File.separator
+ zipPath);
if (!zipFolder.exists()) {
zipFolder.mkdirs();
}
} else {
File file = new File(targetPath + File.separator
+ zipPath);
if (!file.exists()) {
File pathDir = file.getParentFile();
pathDir.mkdirs();
file.createNewFile();
}

FileOutputStream fos = new FileOutputStream(file);
int bread;
while ((bread = zis.read()) != -1) {
fos.write(bread);
}
fos.close();

}
System.out.println("成功解压:" + zipPath);

} catch (Exception e) {
System.out.println("解压" + zipPath + "失败");
continue;
}
}
zis.close();
is.close();
System.out.println("解压结束");
} catch (Exception e) {
e.printStackTrace();
}

}

/**
* @param args
*/
public static void main(String[] args) {
String targetPath = "D:\\test\\unzip";
String zipFile = "D:\\test\\test.zip";
UnzipFile unzip = new UnzipFile();
unzip.unzipFile(targetPath, zipFile);
}

}



二、解压rar文件
由于WinRAR 是共享软件,并不是开源的,所以解压rar文件的前提是系统已经安装了winrar,比如本人的安装路径是:
C:\\Program Files\\WinRAR\\winrar.exe
然后运用java.lang.Process 的相关知识来运行系统命令行来实现解压的。
winrar 命令行相关参数自己可以搜索下的网上资料很多
    **  
* 解压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 Files\\WinRAR\\winrar.exe";
String unrarCmd = cmd + " x -r -p- -o+ " + absolutePath + " "
+ targetPath;

Runtime rt = Runtime.getRuntime();
Process pre = rt.exec(unrarCmd);
InputStreamReader isr = new InputStreamReader(pre.getInputStream());
BufferedReader bf = new BufferedReader(isr);
String line = null;
while ((line = bf.readLine()) != null) {
line = line.trim();
if ("".equals(line)) {
continue;
}
System.out.println(line);
}

bf.close();
} catch (Exception e) {
System.out.println("解压发生异常");
}
}

/**
* @param args
*/
public static void main(String[] args) {
String targetPath = "D:\\test\\unrar\\";
String rarFilePath = "D:\\test\\test.rar";
UnRarFile unrar = new UnRarFile();
unrar.unRarFile(targetPath, rarFilePath);
}

}



原文出自:http://sjsky.iteye.com/blog/628920
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值