当前位置:网站首页>Zip compression decompression

Zip compression decompression

2022-06-12 21:33:00 Besieged city_ city with high walls

package com.jason.mrht.common.utils;

import java.io.*;

import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/** * Zip Compress / Unzip tool class  *  Realize the compression of all files and empty directories under the target path and its sub paths  * <p>Title: ZipUtil1</p> * <p>Description: </p> * @author fuxinbao * @date 2018 year 5 month 23 On the afternoon of Sunday 3:50:01 */
public class ZipUtils {
    

    /**  Buffer size  */
    private static final int BUFFER = 512;

    /** *  Get all files and empty subdirectories under the given source directory  *  Recursive implementation  * @param srcFile * @return */
    private static List<File> getAllFiles(File srcFile) {
    
        List<File> fileList = new ArrayList<File>();
        File[] tmp = srcFile.listFiles();

        for (int i = 0; i < tmp.length; i++) {
    

            if (tmp[i].isFile()) {
    
                fileList.add(tmp[i]);
                System.out.println("add file: "+tmp[i].getName());
            }

            if (tmp[i].isDirectory()) {
    
                if (tmp[i].listFiles().length!=0){
    // If it's not an empty directory , Then recursively add the directories and files under it 
                    fileList.addAll(getAllFiles(tmp[i]));
                }
                else{
    // If it's an empty directory , Add this directory to fileList
                    fileList.add(tmp[i]);
                    System.out.println("add empty dir: "+tmp[i].getName());
                }
            }
        }    // end for

        return fileList;
    }

    /** *  Take the relative path  *  Get the relative path of the file under the compressed source path according to the file name and compressed source path  * * @param dirPath  Compressed source path  * @param file * * @return  Relative paths  */
    private static String getRelativePath(String dirPath, File file) {
    
        File dir = new File(dirPath);
        String relativePath = file.getName();

        while (true) {
    
            file = file.getParentFile();

            if (file == null) {
    
                break;
            }

            if (file.equals(dir)) {
    
                break;
            } else {
    
                relativePath = file.getName() + "/" + relativePath;
            }
        }    // end while

        return relativePath;
    }

    /** *  create a file  *  According to the file name in the compressed package and the decompression destination path , Create the decompression target file , *  Generate intermediate Directory  * @param dstPath  Decompression destination path  * @param fileName  File name in the compressed package  * @return  Unzip the target file  * @throws IOException */
    private static File createFile(String dstPath, String fileName) throws IOException {
    
        String[] dirs = fileName.split("/");// Decompose all levels of directories of file names 
        File     file = new File(dstPath);

        if (dirs.length > 1) {
    // The file has a parent directory 
            for (int i = 0; i < dirs.length - 1; i++) {
    
                file = new File(file, dirs[i]);// Create file objects in turn and know the upper directory of the file 
            }

            if (!file.exists()) {
    
                file.mkdirs();// If the directory corresponding to the file does not exist , Create 
                System.out.println("mkdirs: " + file.getCanonicalPath());
            }

            file = new File(file, dirs[dirs.length - 1]);// create a file 

            return file;
        } else {
    
            if (!file.exists()) {
    
                file.mkdirs();// If the directory of the target path does not exist , Create 
                System.out.println("mkdirs: " + file.getCanonicalPath());
            }

            file = new File(file, dirs[0]);// create a file 

            return file;
        }
    }

    /** *  Decompression method  * * * @param zipFileName  Compressed file name  * @param dstPath  Unzip the target path  * * @return */
    public static boolean unzip(String zipFileName, String dstPath) {
    
        System.out.println("zip uncompressing...");

        try {
    
            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFileName));
            ZipEntry zipEntry = null;
            byte[] buffer = new byte[BUFFER];// Buffer 
            int readLength = 0;// The length of each reading 

            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
    
                if (zipEntry.isDirectory()) {
    // if zip Entry directory , You need to create this directory 
                    File dir = new File(dstPath + "/" + zipEntry.getName());

                    if (!dir.exists()) {
    
                        dir.mkdirs();
                        System.out.println("mkdirs: " + dir.getCanonicalPath());

                        continue;// Jump out of 
                    }
                }

                File file = createFile(dstPath, zipEntry.getName());// If it's a document , You need to create this file 

                System.out.println("file created: " + file.getCanonicalPath());

                OutputStream outputStream = new FileOutputStream(file);

                while ((readLength = zipInputStream.read(buffer, 0, BUFFER)) != -1) {
    
                    outputStream.write(buffer, 0, readLength);
                }

                outputStream.close();
                System.out.println("file uncompressed: " + file.getCanonicalPath());
            }    // end while
        } catch (FileNotFoundException e) {
    
            System.out.println(e.getMessage());
            e.printStackTrace();
            System.out.println("unzip fail!");

            return false;
        } catch (IOException e) {
    
            System.out.println(e.getMessage());
            e.printStackTrace();
            System.out.println("unzip fail!");

            return false;
        }

        System.out.println("unzip success!");

        return true;
    }

    /** *  Compression method  * ( You can compress empty subdirectories ) * @param srcPath  Compressed source path  * @param zipFileName  Target compressed file  * * @return */
    public static boolean zip(String srcPath, String zipFileName) {
    
        System.out.println("zip compressing...");

        File srcFile = new File(srcPath);
        List<File> fileList = getAllFiles(srcFile);// All files to be compressed 
        byte[] buffer = new byte[BUFFER];// Buffer 
        ZipEntry zipEntry = null;
        int readLength = 0;// The length of each reading 

        try {
    
            ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));

            for (File file : fileList) {
    
                if (file.isFile()){
    // If it's a document , Then compress the file 
                    zipEntry = new ZipEntry(getRelativePath(srcPath, file));
                    zipEntry.setSize(file.length());
                    zipEntry.setTime(file.lastModified());
                    zipOutputStream.putNextEntry(zipEntry);

                    InputStream inputStream = new BufferedInputStream(new FileInputStream(file));

                    while ((readLength = inputStream.read(buffer, 0, BUFFER)) != -1) {
    
                        zipOutputStream.write(buffer, 0, readLength);
                    }

                    inputStream.close();
                    System.out.println("file compressed: " + file.getCanonicalPath());
                }else {
    // If it's a catalog ( Empty directory ) Then write this directory to zip entry 
                    zipEntry = new ZipEntry(getRelativePath(srcPath, file)+"/");
                    zipOutputStream.putNextEntry(zipEntry);
                    System.out.println("dir compressed: " + file.getCanonicalPath()+"/");
                }

            }    // end for

            zipOutputStream.close();
        } catch (FileNotFoundException e) {
    
            System.out.println(e.getMessage());
            e.printStackTrace();
            System.out.println("zip fail!");

            return false;
        } catch (IOException e) {
    
            System.out.println(e.getMessage());
            e.printStackTrace();
            System.out.println("zip fail!");

            return false;
        }

        System.out.println("zip success!");

        return true;
    }
}
原网站

版权声明
本文为[Besieged city_ city with high walls]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206122125175832.html