1. import lombok.experimental.UtilityClass;
    2. import org.apache.tools.ant.BuildException;
    3. import org.apache.tools.ant.Project;
    4. import org.apache.tools.ant.taskdefs.Expand;
    5. import org.apache.tools.ant.taskdefs.Zip;
    6. import org.apache.tools.ant.types.FileSet;
    7. import java.io.File;
    8. /**
    9. * @author shizi
    10. * @since 2020/5/18 2:14 PM
    11. */
    12. @UtilityClass
    13. public class Zipper {
    14. public final static String encoding = "GBK";
    15. /**
    16. * 压缩文件和文件夹
    17. *
    18. * @param srcPathname 需要被压缩的文件或文件夹路径
    19. * @param zipFilepath 将要生成的zip文件路径
    20. * @throws BuildException
    21. * @throws RuntimeException
    22. */
    23. public static void zip(String srcPathname, String zipFilepath) throws BuildException, RuntimeException {
    24. File file = new File(srcPathname);
    25. if (!file.exists()) {
    26. throw new RuntimeException("source file or directory " + srcPathname + " does not exist.");
    27. }
    28. Project proj = new Project();
    29. FileSet fileSet = new FileSet();
    30. fileSet.setProject(proj);
    31. // 判断是目录还是文件
    32. if (file.isDirectory()) {
    33. fileSet.setDir(file);
    34. // ant中include/exclude规则在此都可以使用
    35. // 比如:
    36. // fileSet.setExcludes("**/*.txt");
    37. // fileSet.setIncludes("**/*.xls");
    38. } else {
    39. fileSet.setFile(file);
    40. }
    41. Zip zip = new Zip();
    42. zip.setProject(proj);
    43. zip.setDestFile(new File(zipFilepath));
    44. zip.addFileset(fileSet);
    45. zip.setEncoding(encoding);
    46. zip.execute();
    47. System.out.println("compress successed.");
    48. }
    49. /**
    50. * 解压缩文件和文件夹
    51. *
    52. * @param zipFilepath 需要被解压的zip文件路径
    53. * @param destDir 将要被解压到哪个文件夹
    54. * @throws BuildException
    55. * @throws RuntimeException
    56. */
    57. public static void unzip(String zipFilepath, String destDir) throws BuildException, RuntimeException {
    58. if (!new File(zipFilepath).exists()) {
    59. throw new RuntimeException("zip file " + zipFilepath + " does not exist.");
    60. }
    61. Project proj = new Project();
    62. Expand expand = new Expand();
    63. expand.setProject(proj);
    64. expand.setTaskType("unzip");
    65. expand.setTaskName("unzip");
    66. expand.setEncoding(encoding);
    67. expand.setSrc(new File(zipFilepath));
    68. expand.setDest(new File(destDir));
    69. expand.execute();
    70. System.out.println("uncompress successed.");
    71. }
    72. }