java對帶文件夾的文件實現(xiàn)zip壓縮解壓縮記錄

之前記錄過一篇java打包zip壓縮包案例

這里補(bǔ)一下針對帶文件夾的文件壓縮和解壓縮的方法。

新建ZipTest類:

package com.ly.mp.project.test;

import java.io.BufferedOutputStream;
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;

import com.alibaba.fastjson.JSONObject;
import com.ly.mp.project.utils.IOCloseUtil;

public class ZipTest {
    /**
     * 解壓到指定目錄
     */
    public static List<String> unZipFiles(String zipPath,String descDir)throws IOException
    {
        return unZipFiles(new File(zipPath), descDir);
    }
    /**
     * 解壓文件到指定目錄
     */
    @SuppressWarnings("rawtypes")
    public static List<String> unZipFiles(File zipFile,String descDir)throws IOException
    {
        List<String> pathList = new ArrayList<>();
        File pathFile = new File(descDir);
        if(!pathFile.exists())
        {
            pathFile.mkdirs();
        }
        //解決zip文件中有中文目錄或者中文文件
        try (ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"))) {
            for(Enumeration entries = zip.entries(); entries.hasMoreElements();){
                ZipEntry entry = (ZipEntry)entries.nextElement();
                String zipEntryName = entry.getName();
                InputStream in = zip.getInputStream(entry);
                String outPath = (descDir+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;
                }
                //輸出文件路徑信息
                System.out.println(outPath);
                pathList.add(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();
            }
        }
        return pathList;
    }
    
    
    public static void folderToZip (String sourceDirPath, String zipFilePath, String zipFileName) throws IOException{
        File sourceFile = new File(sourceDirPath);
        if (!sourceFile.exists()) {
            throw new IOException("待壓縮的文件目錄:" + sourceDirPath + " 不存在.");
        }
        createDirs(zipFilePath);
        File zipFile = new File(zipFilePath + zipFileName);
        if (zipFile.exists() && !zipFile.delete()) {
            throw new IOException("刪除已存在的文件:" + zipFilePath + zipFileName + " 異常.");
        }
        File[] sourceFiles = sourceFile.listFiles();
        if (sourceFiles == null || sourceFiles.length < 1) {
            throw new IOException("待壓縮的文件目錄:" + sourceDirPath + "為空文件夾.");
        }
        
        ZipOutputStream out = null;
        BufferedOutputStream bos = null;
        try {
            //創(chuàng)建zip輸出流
            out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
            //調(diào)用壓縮函數(shù)
            for(File file : sourceFiles) {
                compress(out, file, file.getName());
            }
            out.flush();
 
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOCloseUtil.close(bos, out);
        }
    }
 
    /**
     * 文件壓縮
     * @param out
     * @param bos
     * @param sourceFile
     * @param base
     */
    public static void compress(ZipOutputStream out, File sourceFile, String base){
        FileInputStream fos = null;
        try {
            //如果路徑為目錄(文件夾)
            if (sourceFile.isDirectory()) {
                //取出文件夾中的文件(或子文件夾)
                File[] flist = sourceFile.listFiles();
                if (flist.length == 0) {//如果文件夾為空,則只需在目的地zip文件中寫入一個目錄進(jìn)入點(diǎn)
                    out.putNextEntry(new ZipEntry(base + "/"));
                } else {//如果文件夾不為空,則遞歸調(diào)用compress,文件夾中的每一個文件(或文件夾)進(jìn)行壓縮
                    for (int i = 0; i < flist.length; i++) {
                        compress(out, flist[i], base + "/" + flist[i].getName());
                    }
                }
            } else {//如果不是目錄(文件夾),即為文件,將文件寫入zip文件中
                out.putNextEntry(new ZipEntry(base));
                fos = new FileInputStream(sourceFile);
 
                int tag;
                //將源文件寫入到zip文件中
                while ((tag = fos.read()) != -1) {
                    out.write(tag);
                }
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOCloseUtil.close(fos);
        }
    }



    /**
     * 創(chuàng)建多層級文件夾
     *
     * @param path
     * @return
     */
    private static boolean createDirs(String path) {
        File fileDir = new File(path);
        if (!fileDir.exists()) {
            return fileDir.mkdirs();
        }
        return true;
    }
    
    public static void main(String[] args) throws IOException {
        String targetFilePath = "d://tmp/zipTest/zipTest.zip";
        String destFilePath = "d://tmp/zipTest/target/";
        //解壓縮
        List<String> filePaths = unZipFiles(targetFilePath, destFilePath);
        System.out.println(JSONObject.toJSONString(filePaths));
        String zipFilePath = "d://tmp/zipTest/";
        String zipFileName = "zipTest1.zip";
        folderToZip(destFilePath, zipFilePath, zipFileName);
    }
}

IOCloseUtil:

package com.ly.mp.project.utils;

import java.io.Closeable;
import java.io.IOException;

public class IOCloseUtil {
    /**
     *   IO流關(guān)閉工具類
     */
    public static void close(Closeable... io) {
        for (Closeable temp : io) {
            try {
                if (null != temp)
                    temp.close();
            } catch (IOException e) {
                System.out.println("" + e.getMessage());
            }
        }
    }
 
    public static <T extends Closeable> void closeAll(T... io) {
        for (Closeable temp : io) {
            try {
                if (null != temp)
                    temp.close();
            } catch (IOException e) {
                System.out.println("" + e.getMessage());
            }
        }
 
    }
}

我們在D:\tmp\zipTest目錄下面放置了一個zipTest.zip的測試文件,里面包含一個test文件夾和test.txt文件,test文件夾里面也包含一個test.txt文件。
我們新建了一個D:\tmp\zipTest\target\文件夾,期望結(jié)果是程序會把zipTest.zip解壓到這個target文件夾里,然后會target文件夾里的所有文件和文件夾進(jìn)行zip打包生成D:\tmp\zipTest\zipTest1.zip
運(yùn)行上面的ZipTest里的main方法,可以得到以下打印結(jié)果:

d://tmp/zipTest/target/test/test.txt
d://tmp/zipTest/target/test.txt
["d://tmp/zipTest/target/test/test.txt","d://tmp/zipTest/target/test.txt"]

實測可以解壓帶文件夾的zip文件,目錄結(jié)構(gòu)也不會有影響,重新打包后的zipTest1.zip也正常。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容