Java中的GZIP文件–压缩和解压缩
时间:2020-01-09 10:35:28 来源:igfitidea点击:
在本文中,我们将介绍如何使用GZIP格式压缩和解压缩Java文件。使用GZIP,我们只能压缩单个文件,而不能压缩目录中的多个文件。
在这篇文章中,请参阅创建tar存档以gzip多个文件的过程GZIP Java中的多个文件创建Tar存档
Java GZIP示例-压缩和解压缩文件
GZIP压缩–使用GZIPOutputStream压缩文件。我们需要使用InputStream读取文件并将其写入GZIPOutputStream以获得GZIP格式的文件。
GZIP解压缩–使用GZIPInputStream解压缩文件。我们需要从GZIPInputStream读取文件并将其写入输出流以获取解压缩的文件。
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; public class GzipFile { public static void main(String[] args) { String SOURCE_FILE = "/home/theitroad/Documents/theitroad/postend"; String GZIPPED_FILE = "/home/theitroad/Documents/theitroad/postend.gz"; String DECOMPRESSED_FILE = "/home/theitroad/Documents/theitroad/postend_decomp.txt"; GzipFile gzip = new GzipFile(); // call to GZIP compress gzip.compressGZipFile(SOURCE_FILE, GZIPPED_FILE); // call to GZIP decompress gzip.deCompressGZipFile(GZIPPED_FILE, DECOMPRESSED_FILE); } public void compressGZipFile(String sourceFile, String gzipFile) { FileInputStream fis = null; FileOutputStream fos = null; GZIPOutputStream gZIPOutputStream = null; try { fis = new FileInputStream(sourceFile); fos = new FileOutputStream(gzipFile); gZIPOutputStream = new GZIPOutputStream(fos); byte[] buffer = new byte[1024]; int len; while((len = fis.read(buffer)) > 0){ gZIPOutputStream.write(buffer, 0, len); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { if(fis != null) { fis.close(); } if(gZIPOutputStream != null) { gZIPOutputStream.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void deCompressGZipFile(String gzipFile, String destFile) { FileInputStream fis = null; FileOutputStream fos = null; GZIPInputStream gZIPInputStream = null; try { fis = new FileInputStream(gzipFile); gZIPInputStream = new GZIPInputStream(fis); fos = new FileOutputStream(destFile); byte[] buffer = new byte[1024]; int len; while((len = gZIPInputStream.read(buffer)) > 0){ fos.write(buffer, 0, len); } }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { if(gZIPInputStream != null) { gZIPInputStream.close(); } if(fos != null) { fos.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }