Sunday, 24 April 2016

How to compress and decompress files in GZIP format ?


Compress a file in GZIP format
Gzip is not a ZIP tool, it only use to compress a file into a “.gz” format, not compress several files into a single archive.

String OUTPUT_GZIP_FILE = "/home/shaan/file1.gz";
String SOURCE_FILE = "/home/shaan/file1.txt";
byte[] buffer = new byte[1024];

GZIPOutputStream gzos =
       new GZIPOutputStream(new FileOutputStream(OUTPUT_GZIP_FILE));
FileInputStream in = new FileInputStream(SOURCE_FILE);

int len;
while ((len = in.read(buffer)) > 0) {
  gzos.write(buffer, 0, len);
}

in.close();
gzos.finish();

gzos.close();


Decompress file from GZIP file
String INPUT_GZIP_FILE = "/home/shaan/file1.gz";
String OUTPUT_FILE = "/home/shaan/file1.txt";
byte[] buffer = new byte[1024];

GZIPInputStream gzis =
        new GZIPInputStream(new FileInputStream(INPUT_GZIP_FILE));
FileOutputStream out = new FileOutputStream(OUTPUT_FILE);

int len;
while ((len = gzis.read(buffer)) > 0) {
  out.write(buffer, 0, len);
}

gzis.close();

out.close();

No comments:

Post a Comment

Note: only a member of this blog may post a comment.