User Tools

Site Tools


java-example:unzipfile

解压文件

package com.xiaosq.example;
 
import org.apache.commons.lang3.StringUtils;
 
import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
 
/**
 * @author Morgan.L
 * @version 1.0
 * @date 2017/9/13 17:18
 */
public class MainUnzipFile {
 
  public static void main(String[] args) {
    String zipFilePath = convertFilePath("C:\\git3/");
    String zipFileName = "kk.zip";
    String descPath = convertFilePath("C:\\git3");
 
    String realDescPath = descPath + zipFileName.split("\\.")[0] + "/";
 
    try {
      unZipFiles(zipFilePath + zipFileName, realDescPath);
    } catch (IOException e) {
      e.printStackTrace();
    }
    File indexHtml = new File(realDescPath + "index.html");
    File indexJson = new File(realDescPath + "index.json");
    if (indexHtml.exists() && indexJson.exists()) {
      System.out.println("获取文件正常。");
    } else {
      System.out.println("index.html或者index.json有一个可能不存在");
    }
  }
 
 
  @SuppressWarnings("rawtypes")
  public static void unZipFiles(String zipFile, String descPath)
      throws IOException {
    //确认目标路径
    File pathFile = new File(descPath);
    if (!pathFile.exists()) {
      pathFile.mkdirs();
    }
 
    //确认zip文件
    ZipFile zip = new ZipFile(zipFile);
 
    for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
      ZipEntry entry = (ZipEntry) entries.nextElement();
      String zipEntryName = entry.getName();
      InputStream in = zip.getInputStream(entry);
      String outPath = descPath + zipEntryName;
 
      //判断路径是否存在,不存在则创建文件路径
      File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
      if (!file.exists()) {
        file.mkdirs();
      }
      //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
      if (new File(outPath).isDirectory()) {
        continue;
      }
      //输出文件路径信息
      //System.out.println(outPath);
 
      OutputStream 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();
    }
  }
 
 
  //路径格式化,保证路径更准确
  public static String convertFilePath(String filePath) {
    if (StringUtils.isNotBlank(filePath)) {
      filePath = filePath.replaceAll("\\\\", "/");
      if (!filePath.endsWith("/")) {
        filePath = filePath + "/";
      }
    }
    return filePath;
  }
 
}
java-example/unzipfile.txt · Last modified: 2021/08/22 13:36 by morgan0329

Except where otherwise noted, content on this wiki is licensed under the following license: 沪ICP备12046235号-2
Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki