1. 程式人生 > >java壓縮解壓檔案

java壓縮解壓檔案

記錄一下,公司在伺服器中,需要對檔案進行壓縮,然後給使用者下載故記錄一下:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtils {
    
    private ZipUtils(){
    }
    
    public
static void doCompress(String srcFile, String zipFile) throws IOException { doCompress(new File(srcFile), new File(zipFile)); } /** * 檔案壓縮 * @param srcFile 目錄或者單個檔案 * @param zipFile 壓縮後的ZIP檔案 */ public static void doCompress(File srcFile, File zipFile) throws
IOException { ZipOutputStream out = null; try { out = new ZipOutputStream(new FileOutputStream(zipFile)); doCompress(srcFile, out); } catch (Exception e) { throw e; } finally { out.close();//記得關閉資源 } } public
static void doCompress(String filelName, ZipOutputStream out) throws IOException{ doCompress(new File(filelName), out); } public static void doCompress(File file, ZipOutputStream out) throws IOException{ doCompress(file, out, ""); } public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException { if ( inFile.isDirectory() ) { File[] files = inFile.listFiles(); if (files!=null && files.length>0) { for (File file : files) { String name = inFile.getName(); if (!"".equals(dir)) { name = dir + "/" + name; } ZipUtils.doCompress(file, out, name); } } } else { ZipUtils.doZip(inFile, out, dir); } } public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException { String entryName = null; if (!"".equals(dir)) { entryName = dir + "/" + inFile.getName(); } else { entryName = inFile.getName(); } ZipEntry entry = new ZipEntry(entryName); out.putNextEntry(entry); int len = 0 ; byte[] buffer = new byte[1024]; FileInputStream fis = new FileInputStream(inFile); while ((len = fis.read(buffer)) > 0) { out.write(buffer, 0, len); out.flush(); } out.closeEntry(); fis.close(); } public static void main(String[] args) throws IOException { doCompress("D:/data/", "D:/java.zip"); } }

有main方法,執行即可,很實用.

解壓是轉載的,支援原作:

import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


import org.apache.log4j.Logger;

/**
 *  * 壓縮包工具類
 *  
 */
public class UnZip {
    private static final Logger logger = Logger.getLogger(UnZip.class);

    /**
     * 解壓zip檔案 
     *
     * @param zipFile
     * @param unzipFilePath 解壓後存放的路徑
     * @return 返回解壓的路徑資料夾
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static String unzip(File zipFile, String unzipFilePath) throws Exception {
        logger.trace("【update】解壓檔案:" + zipFile + "到路徑:" + unzipFilePath);
        String unzipPath = "";
        //判斷檔案是否存在
        if (!zipFile.exists() || zipFile.length() <= 0) {
            unzipPath = "false";
            return unzipPath;
        }
        if (zipFile.length() <= 0) {
            unzipPath = "false";
            return unzipPath;
        }
        //建立解壓縮檔案儲存的路徑  
        File unzipFileDir = new File(unzipFilePath);
        //的判斷資料夾是否存在如果存在則不建立 如果不存在 則建立
        if (!unzipFileDir.exists() || !unzipFileDir.isDirectory()) {
        //建立資料夾
            unzipFileDir.mkdirs();
        }
        //開始解壓  
        logger.trace("開始解壓....");
        //建立解壓物件
        ZipEntry zipEntry = null;
        //檔案儲存路徑路徑
        String entryFilePath = null;
        //資料夾路徑
        String entryDirPath = null;
        //建立問價物件
        File entryFile = null;
        //建立資料夾物件
        File entryDir = null;
        int index = 0, count = 0, bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
        //建立輸出字元流
        BufferedInputStream bufferedInputStream = null;
        //建立輸入字元流
        BufferedOutputStream bufferedOutputStream = null;
        try {
        //建立壓縮檔案物件
            ZipFile zip = new ZipFile(zipFile);
            Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();
            //第一步迴圈建立資料夾 第二步建立檔案 第三部寫入檔案
            while (entries.hasMoreElements()) {
                zipEntry = entries.nextElement();
                logger.debug("當前的zip物件zipEntry:" + zipEntry.getName());
                logger.debug("當前解壓路徑unzipFilePath:" + unzipFilePath);
                boolean isDir = zipEntry.isDirectory();
                //當前檔案為資料夾
                if (isDir) {
                    logger.debug("當前是個資料夾..." + zipEntry.getName());
                    String dir = zipEntry.getName();
                    entryFilePath = unzipFilePath + dir + "//";
                    logger.debug("當前資料夾的完整路徑是:" + entryFilePath);
                    //定義資料夾
                    entryDir = new File(entryFilePath);
                    //如果資料夾路徑不存在,則建立資料夾  
                    if (!entryDir.exists() || !entryDir.isDirectory()) {
                        entryDir.mkdirs();
                        logger.debug("建立資料夾:" + entryFilePath);
                    }
                } else {
                    //當前是個檔案
                    logger.debug("判斷當前是個檔案:" + zipEntry.getName());
                    entryFilePath = unzipFilePath + zipEntry.getName();
                    logger.debug("當前檔案的完整路徑是entryFilePath:" + entryFilePath);
                    File f = new File(entryFilePath);
                    if (index != -1) {
                        entryDirPath = f.getAbsolutePath().split(f.getName())[0];
                    } else {
                        entryDirPath = "";
                    }
                    logger.debug("entryDirPath:" + entryDirPath);
                    unzipPath = entryDirPath;
                    //定義資料夾
                    entryDir = new File(entryDirPath);
                    //如果資料夾路徑不存在,則建立資料夾  
                    if (!entryDir.exists() || !entryDir.isDirectory()) {
                        entryDir.mkdirs();
                    }
                    //建立解壓檔案  
                    entryFile = new File(entryFilePath);
                    //寫入檔案  
                    bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(entryFile));
                    //讀取檔案
                    bufferedInputStream = new BufferedInputStream(zip.getInputStream(zipEntry));
                    //檔案寫入
                    while ((count = bufferedInputStream.read(buffer, 0, bufferSize)) != -1) {
                        bufferedOutputStream.write(buffer, 0, count);
                    }
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                }
            }
            logger.debug("檔案解壓完畢...重新組裝的路徑是:" + unzipPath);
        } finally {
            try {
                if (null != bufferedInputStream) {
                    bufferedInputStream.close();
                }
                if (null != bufferedOutputStream) {
                    bufferedOutputStream.close();
                }
            } catch (Exception e2) {
            }
        }
        return unzipPath;
    }

    public static void main(String[] args) {
        File zipFile = new File("D:/java.zip");
        System.out.println(zipFile.getName());

        try {
            UnZip.unzip(zipFile, "D:/aa/");
            System.out.println("解壓完成!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

也是有main方法,大家可以合併到一個工具類中,我就不合了,…
轉載:https://blog.csdn.net/qq_39493105/article/details/78421403