CompressIt.java Source code

Java tutorial

Introduction

Here is the source code for CompressIt.java

Source

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class CompressIt {
    public static void main(String[] args) {
        String filename = args[0];
        try {
            File file = new File(filename);
            int length = (int) file.length();
            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);
            ByteArrayOutputStream baos = new ByteArrayOutputStream(length);
            GZIPOutputStream gos = new GZIPOutputStream(baos);
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                gos.write(buffer, 0, bytesRead);
            }
            bis.close();
            gos.close();
            System.out.println("Input Length: " + length);
            System.out.println("Output Length: " + baos.size());
        } catch (FileNotFoundException e) {
            System.err.println("Invalid Filename");
        } catch (IOException e) {
            System.err.println("I/O Exception");
        }
    }
}