Monday, February 14, 2011

Test Locally For GZIP Implementation With Java

Test Locally For GZIP Implementation With Java: "

Today tutorial is about implementing GZIP in plain java application. It was beginning when i wondering to do some compression implementation in my java application. I have trouble with documentation but then i’ve discover that it can be done by spare between compression and decompression file in the application.


The approach is come from student data that can be define as below




Student.java





public class Student implements Serializable {
String name;
int age;
String address;

public Student(String name, int age, String address ) {
this.name = name;
this.age = age;
this.salary = address;
}

public void print() {
System.out.println("Record for: "+name);
System.out.println("Name: "+name);
System.out.println("Age: "+age);
System.out.println("Address: "+address);
}
}



SaveStudent.java




Then we have to create compression file that come up with this java class. Inside this class, we will create runnable class that determine the file stream (FileOutputStream) and Object that correspondence to the stream.




public class SaveEmployee {

public static void main(String argv[]) throws Exception {
// create some objects
Student sarah = new Student("S. Jordan", 18, "St. Tlogomas");
Student sam = new Student("S. McDonald", 19, "St. Landungsari");
// serialize the objects sarah and sam
FileOutputStream fos = new FileOutputStream("file");
GZIPOutputStream gz = new GZIPrOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(gz);
oos.writeObject(sarah);
oos.writeObject(sam);
oos.flush();
oos.close();
fos.close();
}
}

This program will read and create file that named ‘file’. And you can even see the compression result by access it from root of your program directory, and looking for file that named ‘file’.




ReadStudent




This file is decompression thing from ‘file’ that we have mention in SaveStudent.

public class ReadEmployee {
public static void main(String argv[]) throws
Exception{
//deserialize objects sarah and sam
FileInputStream fis = new FileInputStream("db");
GZIPInputStream gs = new GZIPInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(gs);
Student sarah = (Student) ois.readObject();
Student sam = (Student) ois.readObject();
//print the records after reconstruction of state
sarah.print();
sam.print();
ois.close();
fis.close();
}
}

Run it and if you saw the proper output detail about sam and sarah, it mean that decompression working properly.


"

No comments:

Post a Comment

Comments