当前位置:编程学习 > JAVA >>

java解压RAR压缩文件

 

  最近在看java解压缩,发现RAR没有公开加密算法,所以java内部没有提供api解压,当时就觉得郁闷的,结果在网上查阅了一些,发现了一个思路,就是可以调用系统的命令解压文件,下面是解压的RAR文件的方法

 

 

package zip; 

 

import java.io.BufferedReader; 

import java.io.File; 

import java.io.IOException; 

import java.io.InputStreamReader; 

 

/**

 * 解压rar文件

 * 注意:因为rar算法没有公开,我们只能在程序中调用系统安装的rar来解压(系统中必须安装winRAR)

 * @author spring sky

 * Emal: vipa1888@163.com   

 * QQ: 840950105

 * My Name :石明政

 */ 

public class UnRARFile { 

    /**

     * 系统安装的winRAR位置

     */ 

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

    /**

     * 解压方法

     * @param rarFilePath   rar压缩文件的路径

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

     * @throws IOException  IO异常

     */ 

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

    { 

        File f = new File(unFilePath); 

        if(!f.exists())  //如果发现指定解压的路径不存在,创建目录 

        { 

            f.mkdirs(); 

        } 

         

         

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

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

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

         

         

        /**

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

         */ 

        InputStreamReader isr = new InputStreamReader(process.getInputStream());  

        BufferedReader br = new BufferedReader(isr); 

        String str = null; 

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

        { 

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

            { 

                System.out.println(str); 

            } 

        } 

        br.close(); 

    } 

     

 

测试类:

 

 

 

/**

     * 测试

     * @param args

     */ 

    public static void main(String[] args) { 

        String rarPath = "d:\\a.rar"; 

        String unRarPath = "d:\\abc"; 

        try { 

            UnRARFile.unRARFile(rarPath, unRarPath); 

        } catch (IOException e) { 

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

            e.printStackTrace(); 

        } 

    } 

 

需要注意的是:运行程序下面的弹出框

 

\

 

如果没有加密的话,那就直接点击确定就可以了,如果加密就需要密码解压,直接输入密码就可以解压文件了.....

  作者 spring sky

补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,