java 文件压缩及解压缩

java操作windows命令(Rar.exe)执行文件压缩

// String srcPath = "D:\\test";// 被压缩文件夹
String srcPath = "D:\\test.txt";// 被压缩文件
String destPath = "D:\\test.rar";// 压缩后文件
String rarexePath = "C:\\Program Files\\WinRAR\\Rar.exe"; // 电脑系统中WinRAR安装路径 未安装出错
String[] rarcmd = { rarexePath, "a", destPath, srcPath };
Runtime rt = Runtime.getRuntime();
rt.exec(rarcmd);

java操作windows命令(UnRAR.exe)执行文件解压缩

String srcPath = "D:\\test.rar";// 压缩文件
String destPath = "D:\\";// 解压缩后路径
String unrarexePath = "C:\\Program Files\\WinRAR\\UnRAR.exe"; // 电脑系统中WinRAR安装路径 未安装出错
String[] unrarcmd = { unrarexePath, "x", srcPath, destPath };
Runtime rt = Runtime.getRuntime();
rt.exec(unrarcmd);

 java操作第三方jar包执行rar解压缩

// 引用java-unrar-0.3.jar和commons-logging-1.1.3.jar
String rarFile = "d:/test.rar";
String destDir = "d:/";

// 保证文件夹路径最后是"/"或者"\"
char lastChar = destDir.charAt(destDir.length() - 1);
if (lastChar != '/' && lastChar != '\\') {
    destDir += File.separator;
}
// 根据类型,进行相应的解压缩
String type = rarFile.substring(rarFile.lastIndexOf(".") + 1);
if ("rar".equals(type)) {

    // 压缩文件
    Archive a = new Archive(new File(rarFile));
    FileOutputStream fos = null;
    FileHeader fh = a.nextFileHeader();
    while (fh != null) {
        if (!fh.isDirectory()) {
            // 1 根据不同的操作系统拿到相应的 destDirName 和 destFileName
            String compressFileName = fh.getFileNameString().trim();
            String destFileName = "";
            String destDirName = "";
            if (File.separator.equals("/")) {
                // 非windows系统
                destFileName = destDir + compressFileName.replaceAll("\\\\", "/");
                destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));
            } else {
                // windows系统
                destFileName = destDir + compressFileName.replaceAll("/", "\\\\");
                destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));
            }
            // 2 创建文件夹
            File dir = new File(destDirName);
            if (!dir.exists() || !dir.isDirectory()) {
                dir.mkdirs();
            }
            // 3 解压缩文件
            fos = new FileOutputStream(new File(destFileName));
            a.extractFile(fh, fos);
            fos.close();
            fos = null;
        }
        fh = a.nextFileHeader();
        // 关闭流
    }
    a.close();
    a = null;
} else {
    throw new Exception("不是rar格式的压缩包!");
}

 

posted @ 2016-07-08 18:07  蒲木杉  阅读(483)  评论(0编辑  收藏  举报