解壓Zip文件的工具類

兼容JDK7下的java自帶解壓和Apache的解壓塘娶。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.channels.FileChannel;
import java.util.Enumeration;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

public class FileOperatorHelper {
    
    /**
     * 解壓縮
     * 以好壓 壓縮工具的壓縮包(Java自帶解壓)
     * @param zipFile
     * @param decompressPath
     * @throws IOException
     */
    public static void unzipFile(String zipFile, String decompressPath)
            throws IOException {
        int BUFFER = 4096;
        String zename = null;
        InputStream is = null;
        try {
            File dir = new File(decompressPath);
            java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFile);
            Enumeration enumer = zf.entries();
            while (enumer.hasMoreElements()) {
                java.util.zip.ZipEntry ze = (java.util.zip.ZipEntry) enumer.nextElement();
                zename = ze.getName();
                
                // 文件名,不支持中文.
                if (zename == ""
                        || zename.compareTo("\\") == 0
                                                        // 當解壓文件中有文件夾時,解壓失敗,ZF無法關閉,導致對壓縮文件無法操作
                        || zename.compareTo("/") == 0
                        || zename.substring(zename.length() - 1,
                                zename.length()).equals("/")
                        || zename.substring(zename.length() - 1,
                                zename.length()).equals("\\")) {
                    continue;
                }
                File file = new File(dir.getAbsolutePath() + File.separator
                        + zename).getParentFile();
                if (!file.exists()) {
                    file.mkdirs();
                }

                int num;
                
                is= new BufferedInputStream(zf.getInputStream(ze));
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(decompressPath.concat(zename)));
                byte[] buf = new byte[BUFFER];
                while ((num = is.read(buf, 0, BUFFER)) != -1) {
                    out.write(buf, 0, num);

                }
                is.close();
                out.close();
            }
            zf.close();
        } catch (Exception e) {
            if ("MALFORMED".equals(e.getMessage())) {
                unzipFileWinZip(zipFile, decompressPath);
            } else {
                throw new IllegalArgumentException("解壓縮異常", e);
            }
        }

    }
    
    /**
     * 2016年12月30日16:08:15 wx 新增
     * 自己給自己挖了一個坑。不要向客戶推薦軟件。
     * 推薦的多,兼容的多原杂。子子孫孫無窮盡也。
     * 以winZip或者360壓縮工具的壓縮包您机。謹記穿肄!以Apache解壓
     */
    public static void unzipFileWinZip(String zipFile, String decompressPath)
            throws IOException {
        int BUFFER = 4096;
        String zename = null;
        InputStream is = null;
        try {
            File dir = new File(decompressPath);
            ZipFile zf = new ZipFile(zipFile);
            Enumeration enumer = zf.getEntries();
            while (enumer.hasMoreElements()) {
                ZipEntry ze = (ZipEntry) enumer.nextElement();
                zename = ze.getName();
                // 文件名,不支持中文.
                if (zename == ""
                        || zename.compareTo("\\") == 0
                        // 當解壓文件中有文件夾時,解壓失敗际看,ZF無法關閉咸产,導致對壓縮文件無法操作
                        || zename.compareTo("/") == 0
                        || zename.substring(zename.length() - 1,
                                zename.length()).equals("/")
                                || zename.substring(zename.length() - 1,
                                        zename.length()).equals("\\")) {
                    continue;
                }
                File file = new File(dir.getAbsolutePath() + File.separator
                        + zename).getParentFile();
                if (!file.exists()) {
                    file.mkdirs();
                }
                
                int num;
                
                is= new BufferedInputStream(zf.getInputStream(ze));
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(decompressPath.concat(zename)));
                byte[] buf = new byte[BUFFER];
                while ((num = is.read(buf, 0, BUFFER)) != -1) {
                    out.write(buf, 0, num);
                    
                }
                is.close();
                out.close();
            }
            zf.close();
        } catch (Exception e) {
            throw new IllegalArgumentException("解壓縮異常", e);
        }
    }
    
    

    public static void deltree(File directory) {
        if (directory.exists() && directory.isDirectory()) {
            File[] fileArray = directory.listFiles();

            for (int i = 0; i < fileArray.length; i++) {
                if (fileArray[i].isDirectory()) {
                    deltree(fileArray[i]);
                } else {
                    fileArray[i].delete();
                }
            }

            directory.delete();
        }
    }

    public static void deltree(String filepath) {
        File file = new File(filepath);
        deltree(file);
    }

    public static void copyFile(String sourceFileName,
            String destinationFileName) {
        copyFile(new File(sourceFileName), new File(destinationFileName));
    }

    public static void copyFile(File source, File destination) {
        if (!source.exists()) {
            return;
        }

        if ((destination.getParentFile() != null)
                && (!destination.getParentFile().exists())) {
            destination.getParentFile().mkdirs();
        }

        try {
            FileChannel srcChannel = new FileInputStream(source).getChannel();
            FileChannel dstChannel = new FileOutputStream(destination)
                    .getChannel();

            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

            srcChannel.close();
            dstChannel.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public static void copyFile(FileChannel source, File destination) {
        if (source == null) {
            return;
        }

        if ((destination.getParentFile() != null)
                && (!destination.getParentFile().exists())) {
            destination.getParentFile().mkdirs();
        }

        try {

            FileChannel dstChannel = new FileOutputStream(destination)
                    .getChannel();

            dstChannel.transferFrom(source, 0, source.size());

            dstChannel.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    /**
     * 目錄對拷
     * 
     * @param sourcepath
     * @param destpath
     */
    public static void copyPath(String sourcepath, String destpath) {
        File sf = new File(sourcepath);
        if (!sf.exists() || sf.isFile()) {
            return;
        }
        File df = new File(destpath);
        if (!df.exists()) {
            try {
                makedirs(destpath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        File[] fs = sf.listFiles();
        if (fs != null) {
            for (int i = 0; i < fs.length; i++) {
                File tf1 = fs[i];
                File tf2 = new File(destpath + File.separator + tf1.getName());
                copyFile(tf1, tf2);
            }
        }
    }

    /**
     * 壓縮多個文件
     * 
     * @param zipfile
     * @param file
     * @throws Exception
     */
    public static void zip(String zipfile, String[] file) throws Exception {
        FileOutputStream f = new FileOutputStream(zipfile);
        ZipOutputStream out = new ZipOutputStream(new DataOutputStream(f));
        for (int i = 0; i < file.length; i++) {
            FileInputStream stream = new FileInputStream(file[i]);
            DataInputStream in = new DataInputStream(stream);
            out.putNextEntry(new ZipEntry(getFileName(file[i])));
            int c;
            while ((c = in.read()) != -1) {
                out.write(c);
            }
            in.close();
        }
        out.close();
    }

    public static void zip2(String zipfile, String[] file) throws Exception {
        FileOutputStream f = new FileOutputStream(zipfile);
        ZipOutputStream out = new ZipOutputStream(new DataOutputStream(f));
        for (int i = 0; i < file.length; i++) {
            String string = file[i];
            string.replaceAll("\\", "\\\\\\\\");
            FileInputStream stream = new FileInputStream(string);
            DataInputStream in = new DataInputStream(stream);
            out.putNextEntry(new ZipEntry(getFileName(file[i])));
            int c;
            while ((c = in.read()) != -1) {
                out.write(c);
            }
            in.close();
        }
        out.close();
    }

    /**
     * 壓縮指定文件夾中文件
     * 
     * @param zipfile
     *            壓縮后完整名稱
     * @param inputFolder
     *            輸入文件夾
     * @throws Exception
     *             異常
     */
    public static void zip(String zipfile, String inputFolder) throws Exception {
        File d = new File(inputFolder);
        String[] refiles = d.list();
        String[] files = new String[refiles.length];
        for (int i = 0; i < files.length; i++) {
            files[i] = inputFolder + System.getProperty("file.separator")
                    + refiles[i];
        }

        zip(zipfile, files);
    }

    /**
     * 替換文件名稱中分隔符
     * 
     * @param filepath
     * @return
     */
    public static String formatpath(String filepath) {
        String file = StringUtils.replace(filepath, "/",
                System.getProperty("file.separator"));
        file = StringUtils.replace(file, "\\",
                System.getProperty("file.separator"));

        return file;
    }

    /**
     * 得到文件名稱(帶擴展名)
     * 
     * @param selectedFile
     * @return
     */
    public static String getFileName(String selectedFile) {
        String s = formatpath(selectedFile);
        int pos = s.lastIndexOf(System.getProperty("file.separator"));

        if (pos > 0) {
            return s.substring(pos + 1);
        }
        return s;
    }

    /**
     * @param selectedFile
     *            文件完整路徑
     * @return 盤符:\文件夾
     */
    public static String getFilePath(String selectedFile) {

        String s = formatpath(selectedFile);
        int pos = s.lastIndexOf(System.getProperty("file.separator"));

        if (pos > 0) {
            return s.substring(0, pos);
        }
        return "";
    }

    /**
     * 創(chuàng)建路徑
     * 
     * @param filename
     * @return
     * @throws ServiceException
     */
    public static String makedirs(String filename) throws Exception {
        log.info("creating file name == " + filename);
        File f = new File(filename);
        if (f.exists()) {
            log.info("creating file does exist");
            if (f.isFile()) {
                f.delete();
            } else {
                return filename;
            }
        }
        f.mkdirs();
        return filename;
    }

    /**
     * @param delFolder
     *            要刪除的文件夾
     * @return boolean
     */
    public static boolean deleteFolder(File delFolder) {
        if (delFolder == null || !delFolder.exists()) {
            return false;
        }
        // 目錄是否已刪除
        boolean hasDeleted = true;
        // 得到該文件夾下的所有文件夾和文件數(shù)組
        File[] allFiles = delFolder.listFiles();

        for (int i = 0; i < allFiles.length; i++) {
            // 為true時操作
            if (hasDeleted) {
                if (allFiles[i].isDirectory()) {
                    // 如果為文件夾,則遞歸調用刪除文件夾的方法
                    hasDeleted = deleteFolder(allFiles[i]);
                } else if (allFiles[i].isFile()) {
                    // 刪除文件
                    try {
                        if (!allFiles[i].delete()) {
                            // 刪除失敗,返回false
                            hasDeleted = false;
                        }
                    } catch (Exception e) {
                        // 異常,返回false
                        hasDeleted = false;
                    }
                }
            } else {
                // 為false,跳出循環(huán)
                break;
            }
        }
        if (hasDeleted) {
            // 該文件夾已為空文件夾,刪除它
            delFolder.delete();
        }
        return hasDeleted;
    }

    /**
     * @param str
     *            中文字符串
     * @return String
     */
    public static String make8859toGB(String str) {
        try {
            String str8859 = new String(str.getBytes("8859_1"), "GB2312");
            return str8859;
        } catch (UnsupportedEncodingException ioe) {
            return str;
        }
    }

    /**
     * 解壓縮
     * 
     * @param zipfile
     *            壓縮文件名
     * @param dirname
     *            文件路徑
     */
    public static void extract(String zipfile, String dirname) throws Exception {
        try {
            File newdir = new File(dirname);
            if (newdir.exists()) {
                deleteFolder(newdir);
            }
            newdir.mkdir();
            File infile = new File(zipfile);

            // 檢查是否是ZIP文件
            ZipFile zip = new ZipFile(infile);
            zip.close();

            // 建立與目標文件的輸入連接
            ZipInputStream in = new ZipInputStream(new FileInputStream(infile));
            java.util.zip.ZipEntry file = in.getNextEntry();
            int i;
            byte[] c = new byte[1024];
            int slen;

            while (file != null) {

                i = make8859toGB(formatpath(file.getName())).lastIndexOf(
                        System.getProperty("file.separator"));
                if (i != -1) {
                    File dirs = new File(dirname
                            + File.separator
                            + make8859toGB(formatpath(file.getName()))
                                    .substring(0, i));
                    dirs.mkdirs();
                    dirs = null;
                }

                if (file.isDirectory()) {
                    File dirs = new File(
                            make8859toGB(formatpath(file.getName())));
                    dirs.mkdir();
                    dirs = null;
                } else {
                    FileOutputStream out = new FileOutputStream(dirname
                            + File.separator
                            + make8859toGB(formatpath(file.getName())));
                    while ((slen = in.read(c, 0, c.length)) != -1) {
                        out.write(c, 0, slen);
                    }
                    out.close();
                }
                file = in.getNextEntry();
            }
            in.close();
        } catch (ZipException zipe) {
            throw new Exception("不是一個ZIP文件!文件格式錯誤." + zipe.getMessage());
        } catch (IOException ioe) {
            throw new Exception("文件讀取錯誤." + ioe.getMessage());
        } catch (Exception e) {
            throw new Exception("其他錯誤." + e.getMessage());
        }
    }

    /**
     * 刪除文件或者文件夾
     * 
     * @param filepathname
     * @throws IOException
     */
    public static void deleteFile(String filepathname) throws IOException {
        log.info("deleting filename == " + filepathname);
        File file = new File(filepathname);

        if (file.exists()) {
            log.info("file exist");
            if (file.isFile()) {
                log.info("is file");
                file.delete();
            } else {
                log.info("is Directory");
                File[] files = file.listFiles();
                while (files != null && files.length > 0) {
                    if (files[0] != null && files[0].exists()) {
                        if (files[0].isFile()) {
                            files[0].delete();
                        } else {
                            deleteFile(files[0].getPath());
                        }
                        files = file.listFiles();
                    }
                }
                file.delete();
            }
        }
        log.info("deleting file does not exist");
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末仲闽,一起剝皮案震驚了整個濱河市脑溢,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌赖欣,老刑警劉巖屑彻,帶你破解...
    沈念sama閱讀 216,544評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異顶吮,居然都是意外死亡社牲,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評論 3 392
  • 文/潘曉璐 我一進店門悴了,熙熙樓的掌柜王于貴愁眉苦臉地迎上來膳沽,“玉大人汗菜,你說我怎么就攤上這事√羯纾” “怎么了?”我有些...
    開封第一講書人閱讀 162,764評論 0 353
  • 文/不壞的土叔 我叫張陵巡揍,是天一觀的道長痛阻。 經常有香客問我,道長腮敌,這世上最難降的妖魔是什么阱当? 我笑而不...
    開封第一講書人閱讀 58,193評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮糜工,結果婚禮上弊添,老公的妹妹穿的比我還像新娘。我一直安慰自己捌木,他們只是感情好油坝,可當我...
    茶點故事閱讀 67,216評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著刨裆,像睡著了一般澈圈。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上帆啃,一...
    開封第一講書人閱讀 51,182評論 1 299
  • 那天瞬女,我揣著相機與錄音,去河邊找鬼努潘。 笑死诽偷,一個胖子當著我的面吹牛,可吹牛的內容都是我干的疯坤。 我是一名探鬼主播报慕,決...
    沈念sama閱讀 40,063評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼贴膘!你這毒婦竟也來了卖子?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 38,917評論 0 274
  • 序言:老撾萬榮一對情侶失蹤刑峡,失蹤者是張志新(化名)和其女友劉穎洋闽,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體突梦,經...
    沈念sama閱讀 45,329評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡诫舅,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,543評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了宫患。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片刊懈。...
    茶點故事閱讀 39,722評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出虚汛,到底是詐尸還是另有隱情匾浪,我是刑警寧澤,帶...
    沈念sama閱讀 35,425評論 5 343
  • 正文 年R本政府宣布卷哩,位于F島的核電站蛋辈,受9級特大地震影響,放射性物質發(fā)生泄漏将谊。R本人自食惡果不足惜冷溶,卻給世界環(huán)境...
    茶點故事閱讀 41,019評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望尊浓。 院中可真熱鬧逞频,春花似錦、人聲如沸栋齿。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,671評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽褒颈。三九已至柒巫,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間谷丸,已是汗流浹背堡掏。 一陣腳步聲響...
    開封第一講書人閱讀 32,825評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留刨疼,地道東北人泉唁。 一個月前我還...
    沈念sama閱讀 47,729評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像揩慕,于是被迫代替她去往敵國和親亭畜。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,614評論 2 353

推薦閱讀更多精彩內容