1. 程式人生 > >使用java解壓GZip檔案

使用java解壓GZip檔案

Java中有可以直接解壓gzip檔案的輸入流。

/**
     * 獲取檔名(去掉.gz字尾)
     * @param path
     * @return
     */
    public static String getPrefix(String path) {
        int index = path.lastIndexOf('.');
        return path.substring(0, index);
    }

    public static void unGzip(String srcPath) {
        unGzip(new
File(srcPath)); } /** * 解壓Gzip * @param src 壓縮檔案 */ public static void unGzip(File src) { String path = getPrefix(src.getAbsolutePath()); GZIPInputStream gzs = null; BufferedOutputStream bos = null; try { gzs = new GZIPInputStream(new
FileInputStream(src)); bos = new BufferedOutputStream(new FileOutputStream(path)); byte[] buf = new byte[102400]; int len = -1; while ((len = gzs.read(buf)) != -1) { bos.write(buf, 0, len); } bos.flush(); } catch
(FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { FileUtil.close(gzs, bos); } } /** * 關閉流 * @param io */ public static void close(Closeable ...io){ for (Closeable temp : io) { try { if(temp != null){ temp.close(); } } catch (IOException e) { e.printStackTrace(); } } }