文件压缩和解压缩的辅助类

本文介绍了一个Java程序,该程序能够实现文件的压缩与解压缩功能。它使用了Java标准库中的`java.io`和`java.util.zip`包来处理文件及归档操作。程序不仅能够递归地处理文件夹内的所有文件,还能动态显示压缩进度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. import java.io.*;   
  2. import java.util.*;   
  3. import java.util.zip.*;   
  4.   
  5. public class T {   
  6.   public static int bufsize = 8192;   
  7.   
  8.   private String zipBase;   
  9.   
  10.   private int maxFileNameLength;   
  11.   
  12.   private long totalLength;   
  13.   
  14.   private long bytesHandled;   
  15.   
  16.   private String getSpace(int num) {   
  17.     String space = "";   
  18.     for (int i = 0; i < num; i++) {   
  19.       space += " ";   
  20.     }   
  21.     return space;   
  22.   }   
  23.   
  24.   private void getLength(File path) {   
  25.     if (path.isFile()) {   
  26.       totalLength += path.length();   
  27.       if (path.getPath().length() > maxFileNameLength) {   
  28.         maxFileNameLength = path.getPath().length();   
  29.       }   
  30.     } else {   
  31.       File[] fs = path.listFiles();   
  32.       for (int i = 0; i < fs.length; i++) {   
  33.         getLength(fs[i]);   
  34.       }   
  35.     }   
  36.   }   
  37.   
  38.   private String lengthString(long fileLength) {   
  39.     long newValue = 0;   
  40.     String size = null;   
  41.     if (fileLength < 1024) {   
  42.       size = fileLength + " B";   
  43.     } else if (fileLength < (1024 * 1024)) {   
  44.       newValue = fileLength / 1024;   
  45.       size = newValue + " KB";   
  46.     } else if (fileLength < (1024 * 1024 * 1024)) {   
  47.       newValue = fileLength / (1024 * 1024);   
  48.       size = newValue + " MB";   
  49.     } else {   
  50.       newValue = fileLength / (1024 * 1024 * 1024);   
  51.       size = newValue + " GB";   
  52.     }   
  53.     return size;   
  54.   }   
  55.   
  56.   public void zip(String path) throws Exception {   
  57.     zip(path, null);   
  58.   }   
  59.   
  60.   public void zip(String path, String dest) throws Exception {   
  61.     File f = new File(path);   
  62.     if (!f.exists()) {   
  63.       System.out.println("File : " + path + " Not Exists!");   
  64.       return;   
  65.     }   
  66.     getLength(f);   
  67.     System.out.println("total " + lengthString(totalLength) + " to zip");   
  68.     String path2 = "";   
  69.     for (int i = 0; i < path.length(); i++) {   
  70.       char c = path.charAt(i);   
  71.       if (c == '\\') {   
  72.         c = '/';   
  73.       }   
  74.       path2 += c;   
  75.     }   
  76.     path = path2;   
  77.     zipBase = path.substring(path.lastIndexOf("/") == -1 ? 0 : path.lastIndexOf("/") + 1);   
  78.     if (dest == null) {   
  79.       if (f.isFile()) {   
  80.         if (dest == null) {   
  81.           zipBase = "./";   
  82.           dest = path.substring(0, (path.lastIndexOf(".") == -1 ? path.length() : path   
  83.               .lastIndexOf(".")))   
  84.               + ".zip";   
  85.         }   
  86.       } else {   
  87.         path2 = path.substring(0, path.lastIndexOf("/") == -1 ? path.length() : path   
  88.             .lastIndexOf("/"));   
  89.         if (path.equals(path2)) {   
  90.           dest = ".";   
  91.         }   
  92.         dest = path2   
  93.             + "/"  
  94.             + zipBase.substring(0, (zipBase.lastIndexOf(".") == -1 ? zipBase.length() : zipBase   
  95.                 .lastIndexOf("."))) + ".zip";   
  96.       }   
  97.     }   
  98.     ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(dest));   
  99.     zipFile(f, zipOut);   
  100.     zipOut.close();   
  101.     System.out.print("\r100%\t");   
  102.     System.out.println(path + " has been compressed to zip file : " + dest + getSpace(40));   
  103.   }   
  104.   
  105.   public void zipFile(File f, ZipOutputStream zipOut) throws Exception {   
  106.     if (f.isDirectory()) {   
  107.       File[] fs = f.listFiles();   
  108.       for (int i = 0; i < fs.length; i++) {   
  109.         zipFile(fs[i], zipOut);   
  110.       }   
  111.     } else {   
  112.       String path = f.getPath();   
  113.       FileInputStream fileIn = new FileInputStream(path);   
  114.       String entryName = path;   
  115.       int basePos = path.indexOf(zipBase);   
  116.       if (basePos > 0) {   
  117.         entryName = path.substring(basePos);   
  118.       }   
  119.       ZipEntry theEntry = new ZipEntry(entryName);   
  120.       theEntry.setSize(f.length());   
  121.       zipOut.putNextEntry(theEntry);   
  122.       byte[] buffer = new byte[bufsize];   
  123.       int bytesRead = fileIn.read(buffer, 0, bufsize);   
  124.       bytesHandled += bytesRead;   
  125.       while (bytesRead > 0) {   
  126.         zipOut.write(buffer, 0, bytesRead);   
  127.         bytesRead = fileIn.read(buffer, 0, bufsize);   
  128.         bytesHandled += bytesRead;   
  129.         int percent = (int) (((double) bytesHandled / totalLength) * 100);   
  130.         System.out.print("\r" + percent + "%  ");   
  131.         if (totalLength > 1024 * 1024 * 80) {   
  132.           int j;   
  133.           for (j = 0; j < percent % 4 + 1; j++) {   
  134.             System.out.print(">");   
  135.           }   
  136.           for (int x = 0; x < 4 - j; x++) {   
  137.             System.out.print(" ");   
  138.           }   
  139.         }   
  140.         System.out.print("  Compress File " + path + getSpace(maxFileNameLength - path.length()));   
  141.       }   
  142.       fileIn.close();   
  143.       zipOut.closeEntry();   
  144.     }   
  145.   }   
  146.   
  147.   public void unzip(String zipFileName) throws Exception {   
  148.     unzip(zipFileName, null);   
  149.   }   
  150.   
  151.   public void unzip(String zipFileName, String dest) throws Exception {   
  152.     File f = new File(zipFileName);   
  153.     if (!f.exists()) {   
  154.       System.out.println("Zip File : " + zipFileName + " Not Exists!");   
  155.       return;   
  156.     }   
  157.     byte[] buffer = new byte[bufsize];   
  158.     ZipFile zf = new ZipFile(zipFileName);   
  159.     ZipEntry theEntry = null;   
  160.     Enumeration enumer = zf.entries();   
  161.     while (enumer.hasMoreElements()) {   
  162.       theEntry = (ZipEntry) enumer.nextElement();   
  163.       totalLength += theEntry.getSize();   
  164.       if (theEntry.getName().length() > maxFileNameLength) {   
  165.         maxFileNameLength = theEntry.getName().length();   
  166.       }   
  167.     }   
  168.     System.out.println("Zip File " + lengthString(f.length()) + " and Total "  
  169.         + lengthString(totalLength) + " Data to unzip");   
  170.     enumer = zf.entries();   
  171.     while (enumer.hasMoreElements()) {   
  172.       theEntry = (ZipEntry) enumer.nextElement();   
  173.       String entryName = theEntry.getName();   
  174.       String entryName2 = "";   
  175.       for (int i = 0; i < entryName.length(); i++) {   
  176.         char c = entryName.charAt(i);   
  177.         if (c == '\\') {   
  178.           c = '/';   
  179.         }   
  180.         entryName2 += c;   
  181.       }   
  182.       entryName = entryName2;   
  183.       zipBase = ".";   
  184.       if (dest != null) {   
  185.         if (dest.endsWith("/")) {   
  186.           dest = dest.substring(0, dest.length() - 1);   
  187.         }   
  188.         zipBase = dest;   
  189.       }   
  190.       String tmpFolder = zipBase;   
  191.       int begin = 0;   
  192.       int end = 0;   
  193.       while (true) {   
  194.         end = entryName.indexOf("/", begin);   
  195.         if (end == -1) {   
  196.           break;   
  197.         }   
  198.         tmpFolder += "/" + entryName.substring(begin, end);   
  199.         begin = end + 1;   
  200.         f = new File(tmpFolder);   
  201.         if (!f.exists()) {   
  202.           f.mkdir();   
  203.         }   
  204.       }   
  205.       OutputStream os = new FileOutputStream(zipBase + "/" + entryName);   
  206.       InputStream is = zf.getInputStream(theEntry);   
  207.       int bytesRead = is.read(buffer, 0, bufsize);   
  208.       bytesHandled += bytesRead;   
  209.       while (bytesRead > 0) {   
  210.         os.write(buffer, 0, bytesRead);   
  211.         bytesRead = is.read(buffer, 0, bufsize);   
  212.         bytesHandled += bytesRead;   
  213.         System.out.print("\r");   
  214.         int percent = (int) (((double) bytesHandled / totalLength) * 100);   
  215.         System.out.print("\r" + percent + "%  ");   
  216.         if (totalLength > 1024 * 1024 * 80) {   
  217.           int j;   
  218.           for (j = 0; j < percent % 4 + 1; j++) {   
  219.             System.out.print(">");   
  220.           }   
  221.           for (int x = 0; x < 4 - j; x++) {   
  222.             System.out.print(" ");   
  223.           }   
  224.         }   
  225.         System.out.print("  Unzip File " + entryName   
  226.             + getSpace(maxFileNameLength - entryName.length()));   
  227.       }   
  228.       is.close();   
  229.       os.close();   
  230.     }   
  231.     System.out.println("\r100%  Zip File : " + zipFileName + " has been unCompressed to " + dest   
  232.         + "/ !" + getSpace(40));   
  233.   }   
  234.   
  235.   public static void main(String[] args) throws Exception {   
  236.     if (args.length < 2) {   
  237.       System.out.println("usage : java T -zip[-unzip] filename");   
  238.       return;   
  239.     }   
  240.     T zip = new T();   
  241.     String dest = null;   
  242.     if (args[0].equals("-zip")) {   
  243.       if (args.length > 2) {   
  244.         dest = args[2];   
  245.       }   
  246.       zip.zip(args[1], dest);   
  247.     }   
  248.     if (args[0].equals("-unzip")) {   
  249.       if (args.length > 2) {   
  250.         dest = args[2];   
  251.       }   
  252.       zip.unzip(args[1], dest);   
  253.     }   
  254.   }   
  255. }  
import java.io.*;
import java.util.*;
import java.util.zip.*;

public class T {
  public static int bufsize = 8192;

  private String zipBase;

  private int maxFileNameLength;

  private long totalLength;

  private long bytesHandled;

  private String getSpace(int num) {
    String space = "";
    for (int i = 0; i < num; i++) {
      space += " ";
    }
    return space;
  }

  private void getLength(File path) {
    if (path.isFile()) {
      totalLength += path.length();
      if (path.getPath().length() > maxFileNameLength) {
        maxFileNameLength = path.getPath().length();
      }
    } else {
      File[] fs = path.listFiles();
      for (int i = 0; i < fs.length; i++) {
        getLength(fs[i]);
      }
    }
  }

  private String lengthString(long fileLength) {
    long newValue = 0;
    String size = null;
    if (fileLength < 1024) {
      size = fileLength + " B";
    } else if (fileLength < (1024 * 1024)) {
      newValue = fileLength / 1024;
      size = newValue + " KB";
    } else if (fileLength < (1024 * 1024 * 1024)) {
      newValue = fileLength / (1024 * 1024);
      size = newValue + " MB";
    } else {
      newValue = fileLength / (1024 * 1024 * 1024);
      size = newValue + " GB";
    }
    return size;
  }

  public void zip(String path) throws Exception {
    zip(path, null);
  }

  public void zip(String path, String dest) throws Exception {
    File f = new File(path);
    if (!f.exists()) {
      System.out.println("File : " + path + " Not Exists!");
      return;
    }
    getLength(f);
    System.out.println("total " + lengthString(totalLength) + " to zip");
    String path2 = "";
    for (int i = 0; i < path.length(); i++) {
      char c = path.charAt(i);
      if (c == '\\') {
        c = '/';
      }
      path2 += c;
    }
    path = path2;
    zipBase = path.substring(path.lastIndexOf("/") == -1 ? 0 : path.lastIndexOf("/") + 1);
    if (dest == null) {
      if (f.isFile()) {
        if (dest == null) {
          zipBase = "./";
          dest = path.substring(0, (path.lastIndexOf(".") == -1 ? path.length() : path
              .lastIndexOf(".")))
              + ".zip";
        }
      } else {
        path2 = path.substring(0, path.lastIndexOf("/") == -1 ? path.length() : path
            .lastIndexOf("/"));
        if (path.equals(path2)) {
          dest = ".";
        }
        dest = path2
            + "/"
            + zipBase.substring(0, (zipBase.lastIndexOf(".") == -1 ? zipBase.length() : zipBase
                .lastIndexOf("."))) + ".zip";
      }
    }
    ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(dest));
    zipFile(f, zipOut);
    zipOut.close();
    System.out.print("\r100%\t");
    System.out.println(path + " has been compressed to zip file : " + dest + getSpace(40));
  }

  public void zipFile(File f, ZipOutputStream zipOut) throws Exception {
    if (f.isDirectory()) {
      File[] fs = f.listFiles();
      for (int i = 0; i < fs.length; i++) {
        zipFile(fs[i], zipOut);
      }
    } else {
      String path = f.getPath();
      FileInputStream fileIn = new FileInputStream(path);
      String entryName = path;
      int basePos = path.indexOf(zipBase);
      if (basePos > 0) {
        entryName = path.substring(basePos);
      }
      ZipEntry theEntry = new ZipEntry(entryName);
      theEntry.setSize(f.length());
      zipOut.putNextEntry(theEntry);
      byte[] buffer = new byte[bufsize];
      int bytesRead = fileIn.read(buffer, 0, bufsize);
      bytesHandled += bytesRead;
      while (bytesRead > 0) {
        zipOut.write(buffer, 0, bytesRead);
        bytesRead = fileIn.read(buffer, 0, bufsize);
        bytesHandled += bytesRead;
        int percent = (int) (((double) bytesHandled / totalLength) * 100);
        System.out.print("\r" + percent + "%  ");
        if (totalLength > 1024 * 1024 * 80) {
          int j;
          for (j = 0; j < percent % 4 + 1; j++) {
            System.out.print(">");
          }
          for (int x = 0; x < 4 - j; x++) {
            System.out.print(" ");
          }
        }
        System.out.print("  Compress File " + path + getSpace(maxFileNameLength - path.length()));
      }
      fileIn.close();
      zipOut.closeEntry();
    }
  }

  public void unzip(String zipFileName) throws Exception {
    unzip(zipFileName, null);
  }

  public void unzip(String zipFileName, String dest) throws Exception {
    File f = new File(zipFileName);
    if (!f.exists()) {
      System.out.println("Zip File : " + zipFileName + " Not Exists!");
      return;
    }
    byte[] buffer = new byte[bufsize];
    ZipFile zf = new ZipFile(zipFileName);
    ZipEntry theEntry = null;
    Enumeration enumer = zf.entries();
    while (enumer.hasMoreElements()) {
      theEntry = (ZipEntry) enumer.nextElement();
      totalLength += theEntry.getSize();
      if (theEntry.getName().length() > maxFileNameLength) {
        maxFileNameLength = theEntry.getName().length();
      }
    }
    System.out.println("Zip File " + lengthString(f.length()) + " and Total "
        + lengthString(totalLength) + " Data to unzip");
    enumer = zf.entries();
    while (enumer.hasMoreElements()) {
      theEntry = (ZipEntry) enumer.nextElement();
      String entryName = theEntry.getName();
      String entryName2 = "";
      for (int i = 0; i < entryName.length(); i++) {
        char c = entryName.charAt(i);
        if (c == '\\') {
          c = '/';
        }
        entryName2 += c;
      }
      entryName = entryName2;
      zipBase = ".";
      if (dest != null) {
        if (dest.endsWith("/")) {
          dest = dest.substring(0, dest.length() - 1);
        }
        zipBase = dest;
      }
      String tmpFolder = zipBase;
      int begin = 0;
      int end = 0;
      while (true) {
        end = entryName.indexOf("/", begin);
        if (end == -1) {
          break;
        }
        tmpFolder += "/" + entryName.substring(begin, end);
        begin = end + 1;
        f = new File(tmpFolder);
        if (!f.exists()) {
          f.mkdir();
        }
      }
      OutputStream os = new FileOutputStream(zipBase + "/" + entryName);
      InputStream is = zf.getInputStream(theEntry);
      int bytesRead = is.read(buffer, 0, bufsize);
      bytesHandled += bytesRead;
      while (bytesRead > 0) {
        os.write(buffer, 0, bytesRead);
        bytesRead = is.read(buffer, 0, bufsize);
        bytesHandled += bytesRead;
        System.out.print("\r");
        int percent = (int) (((double) bytesHandled / totalLength) * 100);
        System.out.print("\r" + percent + "%  ");
        if (totalLength > 1024 * 1024 * 80) {
          int j;
          for (j = 0; j < percent % 4 + 1; j++) {
            System.out.print(">");
          }
          for (int x = 0; x < 4 - j; x++) {
            System.out.print(" ");
          }
        }
        System.out.print("  Unzip File " + entryName
            + getSpace(maxFileNameLength - entryName.length()));
      }
      is.close();
      os.close();
    }
    System.out.println("\r100%  Zip File : " + zipFileName + " has been unCompressed to " + dest
        + "/ !" + getSpace(40));
  }

  public static void main(String[] args) throws Exception {
    if (args.length < 2) {
      System.out.println("usage : java T -zip[-unzip] filename");
      return;
    }
    T zip = new T();
    String dest = null;
    if (args[0].equals("-zip")) {
      if (args.length > 2) {
        dest = args[2];
      }
      zip.zip(args[1], dest);
    }
    if (args[0].equals("-unzip")) {
      if (args.length > 2) {
        dest = args[2];
      }
      zip.unzip(args[1], dest);
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值