Java檔案壓縮

weixin_34007291發表於2017-04-12

從接觸計算機開始,便知道了壓縮檔案的存在,剛開始不解(本來我一次就可以開啟檔案,現在卻多了一步,乃是解壓。。。)到了後來,我才慢慢明白壓縮的重要性,除了節省空間,還節省了時間。有時候壓縮檔案的結果會讓你吃驚,大概在原檔案的50%左右,這樣在網路端傳輸的時間將縮短一半。由此可見,它是有多麼的重要。

單個檔案壓縮

首選GZIP

public static void compress(File source, File gzip) {
    if(source == null || gzip == null) 
        throw new NullPointerException();
    BufferedReader reader = null;
    BufferedOutputStream bos = null;
    try {
        //讀取文字檔案可以字元流讀取
        reader = new BufferedReader(new FileReader(source));
        //對於GZIP輸出流,只能使用位元組流
        bos = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(gzip)));
        String data;
        while((data = reader.readLine()) != null) {
            bos.write(data.getBytes());
        }
    }  catch (IOException e) {
        throw new RuntimeException(e);
    }  finally {
        try {
            if(reader != null)
                reader.close();
            if(bos != null) 
                bos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        
    }
}

多檔案壓縮

public static void compressMore(File[] files, File outFile) {
    if(files == null || outFile == null) 
        throw new NullPointerException();
    ZipOutputStream zipStream = null;
    try {
        //用校驗流確保輸出資料的完整性
        CheckedOutputStream cos = new CheckedOutputStream(new FileOutputStream(outFile), new Adler32());
        //用緩衝位元組輸出流進行包裝
        zipStream = new ZipOutputStream(new BufferedOutputStream(cos));
        for (File file : files) {
            if(file != null) {
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
                try {
                    //新增實體到流中,實際上只需要指定檔名稱
                    zipStream.putNextEntry(new ZipEntry(file.getName()));
                    int c;
                    while((c = in.read()) != -1)
                        zipStream.write(c);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    in.close();
                }   
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try{
            if(zipStream != null)
                zipStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

相關文章