java winrar_java 利用系统WinRAR解压缩(zip/rar压缩文件)

本文介绍了一个Java类`UnRARFile`,用于利用系统安装的WinRAR工具进行RAR和ZIP文件的解压缩。通过指定WinRAR的路径和解压缩参数,该类可以执行解压缩操作,并处理可能出现的IO异常和线程中断。代码中特别提到了`cmd`命令的构建,以及如何处理解压缩过程中的输出流。
摘要由CSDN通过智能技术生成

 类名:ZipUtil.java import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry;

package UnZip;

import java.io.BufferedReader;

import java.io.File;

import java.io.IOException;

import java.io.InputStreamReader;

public class UnRARFile {

//系统安装的winRAR位置

private static final String WINRAR_PATH = "C:\\Program Files\\WinRAR\\WinRAR.exe";

/**

* 解压方法

* @param rarFilePath rar压缩文件路径

* @param unFilePath 要解压的到指定的路径

* @throws IOException IO异常

* @throws InterruptedException

*/

public static void unRARFile(String rarFilePath,String unFilePath) throws IOException, InterruptedException

{

File file = new File(unFilePath);

if(!file.exists()) //如果发现指定解压的路径不存在,//通过UnRAR.exe解压RAR压缩文件。 //需要先将“C:\Program Files (x86)\WinRAR”里的两个文件UnRAR.exe和WinRAR.exe复制到C:\Windows下,这样才能通过命令行来解压文件。 void CMyRarDlg::OnBnClickedExtract() { ShellExecute(NULL, NULL, "C:\\Program Fil创建目录

{

file.mkdirs();

}

String cmd = WINRAR_PATH + " x -r -o+ -ibck -y " + rarFilePath+" "+ unFilePath; //需要执行的命令

Runtime runtime = Runtime.getRuntime(); //得到命令对象

Process process = runtime.exec(cmd); //获取执行命令过程中返回的流

//下面是打印出流的内容,查看是否有异常

InputStreamReader isr = new InputStreamReader(process.getInputStream(),"gbk");

BufferedReader br = new BufferedReader(isr);

// String line;

// while((line = br.readLine()) != null){

// System.out.println(line);

// }

// br = new BufferedReader(new InputStreamReader(process.getErrorStream(),"gbk"));

// while((line=br.readLine()) != null){

// System.out.println(line);

// }

// process.waitFor();

String str = null;

while((str=br.readLine())!=null)

{

if(!"".equals(str.trim())&&str!=null) //如果当前行不为空

{

System.out.println(str);

}

}

br.close();

}

public static void main(String args[]) throws InterruptedException{

String rarPath = "C:\\Users\\zm\\Desktop\\Sping3.1.1.rar";

String unRarPath = "C:\\Users\\zm\\Desktop\\test";

try {

UnRARFile.unRARFile(rarPath, unRarPath);

} catch (IOException e) {

System.out.println("出现异常....");

e.printStackTrace();

}

}

}这个不太懂的地方是那个cmd命令,其他的地方都不太难。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值