압축 및 압축 풀기 문서

9411 단어 데이터 구조J#
package com.sjs;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class UtilZip {

    public static void main(String[] args) throws Exception {

        String type = args[0];//       

        //        ,           
        if ("zip" == type) {

            String src = args[1];//    
            String[] srcFile = { src };
            String savePath = args[2];//       
            String destFile = args[3];//       
            // //         
            zip(srcFile, savePath, destFile);
        } else if ("unzip" == type) {

            String savePath = args[1];//             
            String destFile = args[2];//      
            //         
            unZip(destFile, savePath);
        } else {
            throw new RuntimeException(" $1 must be zip or unzip .");
        }

    }

    /**
     * 
     * @param source
     *            
     * @param savePath
     *               
     * @param destFileName
     *              
     * @throws Exception
     * 
     * @Description       
     */
    public static void zip(String[] source, String savePath, String destFileName) throws Exception {

        //            ,       
        init(source, savePath, destFileName);

        File destFile = new File(savePath, destFileName);
        FileInputStream fis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        try {
            //       
            fos = new FileOutputStream(destFile);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("open" + destFile.getAbsolutePath() + "operate fail cause " + e);
        }

        zos = new ZipOutputStream(fos);
        try {
            for (int i = 0; i < source.length; i++) {
                File srcFile = new File(source[i]);

                //      : “c:/home”  “home”;                
                String entryPath = source[i].substring(source[i].indexOf("/") + 1, source[i].length());
                if (srcFile.isDirectory()) {
                    String parent = srcFile.getParent();
                    System.out.println("parent :" + parent);
                    //       
                    zip(zos, srcFile, parent);
                }
                //        
                if (!(srcFile.isDirectory())) {
                    fis = new FileInputStream(new File(source[i]));
                    ZipEntry entry = new ZipEntry(entryPath);
                    zos.putNextEntry(entry);
                    writeFile(fis, zos);
                }
            }
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (zos != null) {
                    zos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 
     * @param zipOutputStream
     *                
     * @param file
     *              
     * @param src
     *                  
     */
    private static void zip(ZipOutputStream zipOutputStream, File file, String src) {
        if (file.isDirectory()) {
            File[] fileList = file.listFiles();
            String entryPath = file.getAbsolutePath().substring(src.length()) + "/";
            try {
                // #####        ,      ,                 
                zipOutputStream.putNextEntry(new ZipEntry(entryPath));
            } catch (Exception e) {
                e.printStackTrace();
            }

            for (int i = 0; i < fileList.length; ++i)
                zip(zipOutputStream, fileList[i], src);
        } else {
            FileInputStream in = null;
            try {
                String fileName = file.getAbsolutePath();
                in = new FileInputStream(file);
                String entryPath = fileName.substring(src.length());
                //       ,   “#####”     ,         ,     ,       (             )
                // entryPath = entryPath.substring(entryPath.lastIndexOf("\\") +
                // 1);
                ZipEntry entry = new ZipEntry(entryPath);
                zipOutputStream.putNextEntry(entry);
                writeFile(in, zipOutputStream);
            } catch (Exception e) {
                throw new RuntimeException("zip file " + file.getAbsolutePath() + " has failed.");
            } finally {
                if (in != null)
                    try {
                        in.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            }
        }
    }

    //         
    private static void writeFile(InputStream fis, OutputStream zos) throws IOException {
        int length = 0;
        byte[] buffer = new byte[1024];
        while ((length = fis.read(buffer)) != -1) {
            zos.write(buffer, 0, length);
        }
        zos.flush();
    }

    /**
     * 
     * @param source
     * @param savePath
     * @param destFileName
     * @Description:           
     */
    private static void init(String[] source, String savePath, String destFileName) {
        if (source == null) {
            throw new IllegalArgumentException("the source file can't be null.");
        }
        if (source.length == 0) {
            throw new IllegalArgumentException("the source file is empty.");
        }

        File sourceFile = null;
        for (int i = 0; i < source.length; i++) {
            sourceFile = new File(source[i]);
            if (!sourceFile.exists()) {
                throw new IllegalArgumentException("the file" + source[i] + "is not exist.");
            }
        }

        File destFile = new File(savePath);
        if (!destFile.exists()) {
            destFile.mkdirs();
        }
    }

    public static String[] unZip(String fileName, String savePath) {
        ArrayList<String> fileList = new ArrayList<String>();

        File unzipfile = null;
        InputStream input = null;
        OutputStream output = null;

        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(new File(fileName));
        } catch (Exception e) {
            throw new RuntimeException("Zip File has Exception " + e);
        }
        Enumeration enumeration = zipFile.entries();

        try {
            do {
                ZipEntry entry = (ZipEntry) enumeration.nextElement();
                unzipfile = new File(savePath, entry.getName());

                input = zipFile.getInputStream(entry);
                if (entry.isDirectory()) {
                    unzipfile.mkdirs();

                }

                if (!(entry.isDirectory())) {
                    output = new FileOutputStream(unzipfile);

                    writeFile(input, output);
                    try {
                        if (input != null)
                            input.close();

                        if (output != null)
                            output.close();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
                fileList.add(entry.getName());
            } while (enumeration.hasMoreElements());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (zipFile != null) {
                    zipFile.close();
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

        String[] str = new String[fileList.size()];
        for (int j = 0; j < fileList.size(); ++j)
            str[j] = ((String) fileList.get(j));

        return str;
    }

}

좋은 웹페이지 즐겨찾기