UnPackageUtils.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package com.onemap.file.utils;
  2. import com.github.junrar.Archive;
  3. import com.github.junrar.rarfile.FileHeader;
  4. import net.lingala.zip4j.core.ZipFile;
  5. import java.io.File;
  6. import java.io.FileOutputStream;
  7. /**
  8. * @author : wangping
  9. * @createDate: 2021/7/12
  10. * @description:解压缩工具
  11. **/
  12. public class UnPackageUtils {
  13. /**
  14. * zip文件解压
  15. *
  16. * @param destPath 解压文件路径
  17. * @param zipFile 压缩文件
  18. * //* @param password 解压密码(如果有)
  19. */
  20. public static void unPackZip(File zipFile, String destPath) {
  21. try {
  22. ZipFile zip = new ZipFile(zipFile);
  23. /*zip4j默认用GBK编码去解压,这里设置编码为GBK的*/
  24. zip.setFileNameCharset("GBK");
  25. zip.extractAll(destPath);
  26. // 如果解压需要密码
  27. // if (zip.isEncrypted()) {
  28. // zip.setPassword(password);
  29. // }
  30. } catch (Exception e) {
  31. }
  32. }
  33. /**
  34. * rar文件解压(不支持有密码的压缩包)
  35. *
  36. * @param rarFile rar压缩包
  37. * @param destPath 解压保存路径
  38. */
  39. public static void unPackRar(File rarFile, String destPath) {
  40. try (Archive archive = new Archive(rarFile)) {
  41. if (null != archive) {
  42. FileHeader fileHeader = archive.nextFileHeader();
  43. File file = null;
  44. while (null != fileHeader) {
  45. // 防止文件名中文乱码问题的处理
  46. String fileName = fileHeader.getFileNameW().isEmpty() ? fileHeader.getFileNameString() : fileHeader.getFileNameW();
  47. if (fileHeader.isDirectory()) {
  48. //是文件夹
  49. file = new File(destPath + File.separator + fileName);
  50. file.mkdirs();
  51. } else {
  52. //不是文件夹
  53. file = new File(destPath + File.separator + fileName.trim());
  54. if (!file.exists()) {
  55. if (!file.getParentFile().exists()) {
  56. // 相对路径可能多级,可能需要创建父目录.
  57. file.getParentFile().mkdirs();
  58. }
  59. file.createNewFile();
  60. }
  61. FileOutputStream os = new FileOutputStream(file);
  62. archive.extractFile(fileHeader, os);
  63. os.close();
  64. }
  65. fileHeader = archive.nextFileHeader();
  66. }
  67. }
  68. } catch (Exception e) {
  69. }
  70. }
  71. }