溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java如何實(shí)現(xiàn)的zip工具類

發(fā)布時(shí)間:2021-04-15 11:51:24 來(lái)源:億速云 閱讀:212 作者:小新 欄目:編程語(yǔ)言

這篇文章主要介紹了Java如何實(shí)現(xiàn)的zip工具類,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

Java可以用來(lái)干什么

Java主要應(yīng)用于:1. web開(kāi)發(fā);2. Android開(kāi)發(fā);3. 客戶端開(kāi)發(fā);4. 網(wǎng)頁(yè)開(kāi)發(fā);5. 企業(yè)級(jí)應(yīng)用開(kāi)發(fā);6. Java大數(shù)據(jù)開(kāi)發(fā);7.游戲開(kāi)發(fā)等。

具體如下:

實(shí)現(xiàn)把zip解壓到指定路徑,把文件夾壓縮到zip,把文件列表壓縮為zip的三個(gè)方法

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
public class ZipUtils
{
  /**
   * 解壓zip到指定路徑
   * @param zipFile 待解壓文件
   * @param descDir 指定解壓路徑
   * @return fileNames 解壓的全部文件名
   * @throws IOException
   */
  public static List<String> unZipFiles(File zipFile, String descDir) throws IOException
 { 
    List<String> fileNames = new ArrayList<String>();
  ZipFile zip = new ZipFile(zipFile,Charset.forName("GBK"));//解決中文文件夾亂碼 
  String name = zip.getName().substring(zip.getName().lastIndexOf('\\')+1, zip.getName().lastIndexOf('.')); 
  File pathFile = new File(descDir+name); 
  if (!pathFile.exists()) 
  { 
   pathFile.mkdirs(); 
  } 
  String outPath = "";
  for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();)
  { 
   ZipEntry entry = (ZipEntry) entries.nextElement(); 
   String zipEntryName = entry.getName(); 
   fileNames.add(zipEntryName);
   InputStream in = zip.getInputStream(entry); 
   outPath = (descDir + name +"/"+ zipEntryName).replaceAll("\\*", "/"); 
   // 判斷路徑是否存在,不存在則創(chuàng)建文件路徑 
   File file = new File(outPath.substring(0, outPath.lastIndexOf('/'))); 
   if (!file.exists()) 
   { 
    file.mkdirs(); 
   } 
   // 判斷文件全路徑是否為文件夾,如果是上面已經(jīng)上傳,不需要解壓 
   if (new File(outPath).isDirectory()) 
   { 
    continue; 
   } 
   // 輸出文件路徑信息 
   FileOutputStream out = new FileOutputStream(outPath); 
   byte[] buf1 = new byte[1024]; 
   int len; 
   while ((len = in.read(buf1)) > 0) { 
    out.write(buf1, 0, len); 
   } 
   in.close(); 
   out.close(); 
  } 
  pathFile.delete();
  return fileNames; 
 }
  /**
   * 壓縮文件夾成zip
   * @param srcDir 待打包的文件夾路徑
   * @param out 打包文件名及存儲(chǔ)路徑
   * @param KeepDirStructure 是否保留文件夾結(jié)構(gòu) 不保留則把文件夾下全部文件都打壓在一起
   * @throws RuntimeException
   */
  public static void docToZip(String srcDir, OutputStream out, boolean KeepDirStructure)throws RuntimeException
  {
    long start = System.currentTimeMillis();
    ZipOutputStream zos = null ;
    try 
    {
      zos = new ZipOutputStream(out);
      File sourceFile = new File(srcDir);
      compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
      long end = System.currentTimeMillis();
      System.out.println("壓縮完成,耗時(shí):" + (end - start) +" ms");
    } catch (Exception e) 
    {
      throw new RuntimeException("zip error from ZipUtils",e);
    }finally
    {
      if(zos != null)
      {
        try 
        {
          zos.close();
        } catch (IOException e)
        {
          e.printStackTrace();
        }
      }
    }
  }
  /**
   * 壓縮成ZIP 將多個(gè)文件大包
   * @param srcFiles 需要壓縮的文件列表
   * @param out     壓縮文件輸出流
   * @throws RuntimeException 壓縮失敗會(huì)拋出運(yùn)行時(shí)異常
   */
  public static void filesToZip(List<File> srcFiles , OutputStream out)throws RuntimeException 
  {
    long start = System.currentTimeMillis();
    ZipOutputStream zos = null ;
    int BUFFER_SIZE = 2 * 1024;
    try 
    {
      zos = new ZipOutputStream(out);
      for (File srcFile : srcFiles) 
      {
        byte[] buf = new byte[BUFFER_SIZE];
        zos.putNextEntry(new ZipEntry(srcFile.getName()));
        int len;
        FileInputStream in = new FileInputStream(srcFile);
        while ((len = in.read(buf)) != -1)
        {
          zos.write(buf, 0, len);
        }
        zos.closeEntry();
        in.close();
      }
      long end = System.currentTimeMillis();
      System.out.println("壓縮完成,耗時(shí):" + (end - start) +" ms");
    } catch (Exception e) 
    {
      throw new RuntimeException("zip error from ZipUtils",e);
    }finally
    {
      if(zos != null)
      {
        try 
        {
          zos.close();
        } catch (IOException e)
        {
          e.printStackTrace();
        }
      }
    }
  }
  /**
   * 遞歸壓縮方法
   * @param sourceFile 源文件
   * @param zos     zip輸出流
   * @param name     壓縮后的名稱
   * @param KeepDirStructure 是否保留原來(lái)的目錄結(jié)構(gòu),true:保留目錄結(jié)構(gòu); 
   *               false:所有文件跑到壓縮包根目錄下(注意:不保留目錄結(jié)構(gòu)可能會(huì)出現(xiàn)同名文件,會(huì)壓縮失敗)
   * @throws Exception
   */
  private static void compress(File sourceFile, ZipOutputStream zos, String name,
      boolean KeepDirStructure) throws Exception
  {
    int BUFFER_SIZE = 2 * 1024;
    byte[] buf = new byte[BUFFER_SIZE];
    if(sourceFile.isFile())
    {
      // 向zip輸出流中添加一個(gè)zip實(shí)體,構(gòu)造器中name為zip實(shí)體的文件的名字
      zos.putNextEntry(new ZipEntry(name));
      // copy文件到zip輸出流中
      int len;
      FileInputStream in = new FileInputStream(sourceFile);
      while ((len = in.read(buf)) != -1)
      {
        zos.write(buf, 0, len);
      }
      // Complete the entry
      zos.closeEntry();
      in.close();
    } else
    {
      File[] listFiles = sourceFile.listFiles();
      if(listFiles == null || listFiles.length == 0)
      {
        // 需要保留原來(lái)的文件結(jié)構(gòu)時(shí),需要對(duì)空文件夾進(jìn)行處理
        if(KeepDirStructure)
        {
          // 空文件夾的處理
          zos.putNextEntry(new ZipEntry(name + "/"));
          // 沒(méi)有文件,不需要文件的copy
          zos.closeEntry();
        }
      }else 
      {
        for (File file : listFiles) 
        {
          // 判斷是否需要保留原來(lái)的文件結(jié)構(gòu)
          if (KeepDirStructure) 
          {
            // 注意:file.getName()前面需要帶上父文件夾的名字加一斜杠,
            // 不然最后壓縮包中就不能保留原來(lái)的文件結(jié)構(gòu),即:所有文件都跑到壓縮包根目錄下了
            compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
          } else 
          {
            compress(file, zos, file.getName(),KeepDirStructure);
          }
        }
      }
    }
  }
}

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Java如何實(shí)現(xiàn)的zip工具類”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI