1. 程式人生 > >Java代碼中解壓RAR文件

Java代碼中解壓RAR文件

tor com .get port void www pri println ()

[java] view plaincopy
  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import de.innosystec.unrar.Archive;
  4. import de.innosystec.unrar.rarfile.FileHeader;
  5. public class UnRARTools {
  6. public void unrar(File sourceRar, File destDir) throws Exception {
  7. Archive archive = null;
  8. FileOutputStream fos = null;
  9. System.out.println("Starting...");
  10. try {
  11. archive = new Archive(sourceRar);
  12. FileHeader fh = archive.nextFileHeader();
  13. int count = 0;
  14. File destFileName = null;
  15. while (fh != null) {
  16. System.out.println((++count) + ") " + fh.getFileNameString());
  17. String compressFileName = fh.getFileNameString().trim();
  18. destFileName = new File(destDir.getAbsolutePath() + "/" + compressFileName);
  19. if (fh.isDirectory()) {
  20. if (!destFileName.exists()) {
  21. destFileName.mkdirs();
  22. }
  23. fh = archive.nextFileHeader();
  24. continue;
  25. }
  26. if (!destFileName.getParentFile().exists()) {
  27. destFileName.getParentFile().mkdirs();
  28. }
  29. fos = new FileOutputStream(destFileName);
  30. archive.extractFile(fh, fos);
  31. fos.close();
  32. fos = null;
  33. fh = archive.nextFileHeader();
  34. }
  35. archive.close();
  36. archive = null;
  37. System.out.println("Finished !");
  38. } catch (Exception e) {
  39. throw e;
  40. } finally {
  41. if (fos != null) {
  42. try {
  43. fos.close();
  44. fos = null;
  45. } catch (Exception e) {
  46. //ignore
  47. }
  48. }
  49. if (archive != null) {
  50. try {
  51. archive.close();
  52. archive = null;
  53. } catch (Exception e) {
  54. //ignore
  55. }
  56. }
  57. }
  58. }
  59. }

需要引用到以下兩個lib.
java-unrar-0.5.jar
http://www.java2s.com/Code/JarDownload/java/java-unrar-0.5.jar.zip
apache-commons-logging.jar
http://www.java2s.com/Code/JarDownload/apache-commons/apache-commons-logging.jar.zip

Java代碼中解壓RAR文件