天天看點

JAVA壓縮、解壓,使用Apache Common Compress包下載下傳連結

近來研究JAVA解壓檔案,于是找到了這個解決辦法: http://commons.apache.org/proper/commons-compress/download_compress.cgi 示例代碼:

/**
     * 解壓縮gz檔案
     * @param file 壓縮封包件
     * @param targetPath 目标檔案夾
     * @param delete 解壓後是否删除原壓縮封包件
     */
    private static void decompressGz(File file, String targetPath,  boolean delete){
        FileInputStream  fileInputStream = null;
        GZIPInputStream gzipIn = null;
        OutputStream out = null;
        String suffix = ".gz";
        try {
            fileInputStream = new FileInputStream(file);
            gzipIn = new GZIPInputStream(fileInputStream);
            // 建立輸出目錄
            createDirectory(targetPath, null);
 
            File tempFile = new File(targetPath + File.separator + file.getName().replace(suffix, ""));
            out = new FileOutputStream(tempFile);
            int count;
            byte data[] = new byte[2048];
            while ((count = gzipIn.read(data)) != -1) {
                out.write(data, 0, count);
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(out != null){
                    out.close();
                }
                if(gzipIn != null){
                    gzipIn.close();
                }
                if(fileInputStream != null){
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }