.gz檔案解壓
阿新 • • 發佈:2019-01-04
GZ壓縮檔案解壓,直接上程式碼:
package test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.GZIPInputStream; /** * 解壓.gz檔案 * @author www * */ public class Gzip { public static final int BUFFER = 1024; public static final String EXT = ".gz"; public static void main(String[] args) { try { deCompress("檔案路徑"); } catch (Exception e) { throw new RuntimeException("解壓檔案失敗!", e); } } /** * 檔案解壓縮 * @param file * @throws Exception */ public static void deCompress(String fileName) throws Exception { File file = new File(fileName); System.out.println(file); decompressFile(file, false); } /** * 檔案解壓縮,是否刪除原檔案 * @param file * @param delete * @throws Exception */ public static void decompressFile (File file,boolean delete) throws Exception{ FileOutputStream fos = new FileOutputStream(file); FileInputStream fis = new FileInputStream(file.getPath().replace(EXT, "")); decompress(fis, fos); fis.close(); fos.flush(); fos.close(); if(delete) { file.delete(); } } /** * 資料解壓縮 * @param is * @param os * @throws Exception */ public static void decompress(InputStream is, OutputStream os) throws Exception { GZIPInputStream gis = new GZIPInputStream(is); int count; byte[] data = new byte[1024]; while((count = gis.read(data,0,BUFFER))!=-1) { os.write(data,0,count); } } }