---
title: "java解压rar文件"
author: "gu6866"
date: "2014-03-01T22:27:08Z"
tags: []
categories: ["编程语言"]
slug: "java-rar"
draft: false
lastmod: "2014-03-01T22:27:08Z"
id: 2024489
url: "https://premier9527.iteye.com/blog/2024489"
---

01. package test;
02. import java.io.File;
03. import java.io.FileOutputStream;
04. import de.innosystec.unrar.Archive;
05. import de.innosystec.unrar.rarfile.FileHeader;
06. public class UnRarFile {
07. /\**
08. \* 解压rar格式压缩包。
09. \* 对应的是java-unrar-0.3.jar，但是java-unrar-0.3.jar又会用到commons-logging-1.1.1.jar
10. \*/
11. private static void unRarFile(String srcRar,String desDir){
12. if(!srcRar.trim().toLowerCase().endsWith(".rar")){
13. System.out.println("非rar文件");
14. return ;
15. }
16. File dir=new File(desDir);
17. if(!dir.exists()){
18. dir.mkdirs();
19. }
20. Archive a=null; //代表一个压缩文件
21. try {
22. a=new Archive(new File(srcRar));
23. if(null!=a){
24. a.getMainHeader().print();//打印文件信息
25. FileHeader fh=a.nextFileHeader();
26. while(null!=fh){
27. if(fh.isDirectory()){//文件夹
28. File fol=new File(desDir+File.separator+fh.getFileNameString());
29. fol.mkdirs();
30. }else{
31. File out=new File(desDir+File.separator+fh.getFileNameString().trim());
32. System.out.println(out.getAbsolutePath());
33. try{
34. if(!out.exists()){
35. if(!out.getParentFile().exists()){
36. out.getParentFile().mkdirs();
37. }
38. out.createNewFile();
39. }
40. FileOutputStream os=new FileOutputStream(out);
41. a.extractFile(fh, os);
42. os.close();
43. }catch (Exception e) {
44. }
45. }
46. fh=a.nextFileHeader();
47. }
48. a.close();
49. }
50. } catch (Exception e) {
51. }
52. }
53. public static void main(String\[] args) {
54. File file=new File("D:\\\\test");
55. for(File f:file.listFiles()){
56. UnRarFile.unRarFile("D:\\\\test\\\\"+f.getName(),"D:\\\\test\\\\"+f.getName().replaceAll(".rar",""));
57. }
58. }
59. }