工具类(zip包解压)

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

public class UnzipUtils {
    public static void unzip(String zipFile, String extractFolder) throws IOException {
        File file = new File(zipFile);
        ZipFile zip = null;

        try {
            int BUFFER = 8192;
            zip = new ZipFile(file);
            File newPath = new File(extractFolder);
            newPath.mkdirs();
            Enumeration zipFileEntries = zip.entries();

            while(true) {
                ZipEntry entry;
                File destFile;
                do {
                    if (!zipFileEntries.hasMoreElements()) {
                        return;
                    }

                    entry = (ZipEntry)zipFileEntries.nextElement();
                    String currentEntry = entry.getName();
                    destFile = new File(newPath, currentEntry);
                    if (!isSubFile(newPath, destFile)) {
                        throw new IOException("Bad zip entry: " + currentEntry);
                    }

                    File destinationParent = destFile.getParentFile();
                    destinationParent.mkdirs();
                } while(entry.isDirectory());

                BufferedInputStream is = null;
                BufferedOutputStream dest = null;

                try {
                    is = new BufferedInputStream(zip.getInputStream(entry));
                    byte[] data = new byte[BUFFER];
                    FileOutputStream fos = new FileOutputStream(destFile);
                    dest = new BufferedOutputStream(fos, BUFFER);

                    int currentByte;
                    while((currentByte = is.read(data, 0, BUFFER)) != -1) {
                        dest.write(data, 0, currentByte);
                    }

                    dest.flush();
                } finally {
                    close((OutputStream)dest);
                    close((InputStream)is);
                }
            }
        } finally {
            close(zip);
        }
    }

    private static IOException close(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }

            return null;
        } catch (IOException var2) {
            return var2;
        }
    }

    private static IOException close(ZipFile zip) {
        try {
            if (zip != null) {
                zip.close();
            }

            return null;
        } catch (IOException var2) {
            return var2;
        }
    }

    private static boolean isSubFile(File parent, File child) throws IOException {
        return child.getCanonicalPath().startsWith(parent.getCanonicalPath() + File.separator);
    }
}

你可能感兴趣的:(工具类,java,开发语言)