// GZIPFile import java.io.*; import java.util.zip.*; /** ..... class GzipFile ..... * Reads the contents of the GZIP file and * Writes data in GZIP file format * * Constructor * public GzipFile(String fileName); * Methods * public void write(byte[] b); * public byte[] read(); * * @author Jeff Zhuk **/

public class GzipFile { private String fileName; private FileOutputStream out; private GZIPOutputStream go; private FileInputStream in; private GZIPInputStream goin; /* Gzip(String iName) constructor is to store a name * in - gzip file name Ex. Gzip gzip = new Gzip("myfile.zip"); * */ public Gzip (String iName){ fileName = iName; } /* writing array of bytes into a compressed file * @param b array of bytes to write */ public void write(byte[] b) { try{ out = new FileOutputStream(fileName); go = new GZIPOutputStream(out); System.out.println("length b.length "+ b.length); go.write(b, 0, b.length); go.close(); out.close(); } catch (IOException ioe) { System.out.println("Gzip: " + ioe); } } /* * reading a compressed file to be decompressed * into an initial array of bytes * @return bb decompressed array of bytes */ public byte[] read() { byte[] bb = null; int byteread = 0; int count = 1; int NumberByteInArray = 0; try{ in=new FileInputStream(fileName); goin = new GZIPInputStream(in); while(count != -1) { byte[] ab = new byte[1]; count = goin.read(ab, count - 1, count); if(count == 1) NumberByteInArray++; } in.close(); } catch (IOException ioe) { System.out.println("Gzip: " + ioe); } try{ in=new FileInputStream(fileName); goin = new GZIPInputStream(in); bb = new byte[NumberByteInArray]; while(byteread != -1) { byteread = goin.read(bb, 0, NumberByteInArray); } in.close(); } catch (IOException ioe) { System.out.println("Gzip: " + ioe); } return bb; } /* main(String args[]) * test method * It writes a string of text into a compressed file * Then it reads the compressed file and restore the string */ public static void main(String args[]){ String str ="Test .... Test"; byte[] b = new byte[str.length()]; //String To Byte str.getBytes(0,str.length(),b,0); GzipFile nn = new GzipFile("itschool.zip"); nn.write(b); byte[] out = nn.read(); String s = new String(out); System.out.println("reading compressed bytes:" + s); }//end main } // End Class

Back to I/O Classes Overview