java 解壓zip包


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ZipTest {

    public static void main(String[] args) {

        //unZip(new File("C:\\Users\\Desktop\\zip\\esException.zip"), "C:\\Users\\Desktop\\zip\\");

        unZipGetFileType(new File("C:\\Users\\Desktop\\zip\\esException.zip"));

    }

//獲取zip下文件名稱文件類型
public static void unZipGetFileType(File srcFile) throws RuntimeException { // 判斷源文件是否存在 if (!srcFile.exists()) { throw new RuntimeException(srcFile.getPath() + "所指文件不存在"); } // 開始解壓 ZipFile zipFile = null; try { zipFile = new ZipFile(srcFile); Enumeration<?> entries = zipFile.entries(); ZipEntry entry = (ZipEntry) entries.nextElement(); String fileName = entry.getName(); System.out.println(fileName); String substring = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()); System.out.println(substring); } catch (Exception e) { throw new RuntimeException("unzip error from ZipUtils", e); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { e.printStackTrace(); } } } } //解壓zip包 public static void unZip(File srcFile, String destDirPath) throws RuntimeException { long start = System.currentTimeMillis(); // 判斷源文件是否存在 if (!srcFile.exists()) { throw new RuntimeException(srcFile.getPath() + "所指文件不存在"); } // 開始解壓 ZipFile zipFile = null; try { zipFile = new ZipFile(srcFile); Enumeration<?> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); System.out.println("解壓" + entry.getName()); // 如果是文件夾,就創建個文件夾 if (entry.isDirectory()) { String dirPath = destDirPath + "/" + entry.getName(); File dir = new File(dirPath); dir.mkdirs(); } else { // 如果是文件,就先創建一個文件,然后用io流把內容copy過去 File targetFile = new File(destDirPath + "/" + entry.getName()); // 保證這個文件的父文件夾必須要存在 if (!targetFile.getParentFile().exists()) { targetFile.getParentFile().mkdirs(); } targetFile.createNewFile(); // 將壓縮文件內容寫入到這個文件中 InputStream is = zipFile.getInputStream(entry); FileOutputStream fos = new FileOutputStream(targetFile); int len; byte[] buf = new byte[1024]; while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } // 關流順序,先打開的后關閉 fos.close(); is.close(); } } long end = System.currentTimeMillis(); System.out.println("解壓完成,耗時:" + (end - start) + " ms"); } catch (Exception e) { throw new RuntimeException("unzip error from ZipUtils", e); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { e.printStackTrace(); } } } } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM