Thursday, 16 February 2012

Java program to compress a file using GZIP

Java can be very efficiently used in compressing files. Java's util package contains certain library classes known as GZIPOutputStream which can be used to compress a file with file extension as .gz. Again we can use GZIPInputStream to decompress any file with extension .gz. Here I will post a function that takes in source and destination file as parameter. It then reads source using FileInputStream and writes the output to destination using GZIPOutputStream. A buffer array is taken which reads certain bytes at a time from source.
Function written below :
     public void gzipFile(String src, String dest) throws Exception {
            FileInputStream in = new FileInputStream(src);
            GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(dest));
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1)
                 out.write(buffer, 0, bytesRead);
            in.close();
            out.close();
     }

No comments:

Post a Comment