import java.io.*; import java.util.zip.*; public class Compress { //------------------------------------------------------------------- // main entry point. Check args. Determine whether to compress or decomp. //------------------------------------------------------------------- protected void go(String[] args) throws IOException { String filename; FileInputStream input; FileOutputStream output; // check command line argument is present if ( args.length != 1 ) { System.out.println("Usage: Compress "); System.exit(10); } // open input file filename = args[0]; input = new FileInputStream(filename); // see whether we should compress or decompress if ( ! filename.endsWith(".crunched") ) { output = new FileOutputStream(filename + ".crunched"); System.out.println("Compressing "+ filename +" to "+ filename +".crunched ..."); compress(input, output); } else { String baseName = filename.substring(0, filename.length()-9); output = new FileOutputStream(baseName + ".out"); System.out.println("Decompressing "+ filename +" to "+ baseName +".out ..."); decompress(input, output); } System.out.println("Done."); } //------------------------------------------------------------------- // Compress/Decompress an input stream to an output stream //------------------------------------------------------------------- protected void compress(InputStream in, OutputStream out) throws IOException { Deflater cruncher; DeflaterOutputStream crunchedOut; cruncher = new Deflater(); // default will do for us crunchedOut = new DeflaterOutputStream(out, cruncher); copyStream(in, crunchedOut); } //------------------------------------------------------------------- protected void decompress(InputStream in, OutputStream out) throws IOException { Inflater uncruncher; InflaterInputStream crunchedIn; uncruncher = new Inflater(); // default will do for us crunchedIn = new InflaterInputStream(in, uncruncher); copyStream(crunchedIn, out); } //------------------------------------------------------------------- // Copy an input stream to an output stream. //------------------------------------------------------------------- protected void copyStream(InputStream in, OutputStream out) throws IOException { int aByte; boolean eof = false; while ( ! eof ) { aByte = in.read(); eof = ( aByte == -1 ); if ( ! eof ) { out.write( (byte) aByte); } } in.close(); out.close(); } //------------------------------------------------------------------- // static main delegates work to object. //------------------------------------------------------------------- public static void main (String[] args) { try { new Compress().go(args); } catch (IOException ioError) { System.out.println("An I/O error occurred: " + ioError); } } } // End of Class Compress