Compress.java |
| /* James Little 5-5-01 I hope this is one of the last programs I have to write in this course. */ package jlittle_ex9.compress; import java.io.*; import java.util.*; import util241.*; public class Compress { private static BufferedInputStream reader; private static BitStreamOutputStream writer; private static String outputfilename = ""; public static void main(String [] args){ String inputfilename = null; Compress a = new Compress(); try{ if (args.length != 0){ inputfilename = args[0]; outputfilename = inputfilename + ".LZW"; // open input streams FileInputStream inFile = new FileInputStream(inputfilename); BufferedInputStream reader = new BufferedInputStream(inFile); //open output streams FileOutputStream outFile = new FileOutputStream(outputfilename); BufferedOutputStream outBuf = new BufferedOutputStream(outFile); writer = new BitStreamOutputStream(outBuf, 12); }else{ reader = new BufferedInputStream(System.in); writer = new BitStreamOutputStream(System.out, 12); } }catch(IOException e){System.out.println("Error: " + e + "\nFilename : "+inputfilename);} a.compress(); } // compression routine public void compress(){ int MAX_VALUE = 4000; Vector string_table = new Vector(); for(int i=0; i<256; i++){ string_table.add(String.valueOf((char)i)); } // System.out.println("I am now compressing..."); int next_code = 256, intStr = 0, intChar=0; try{ intStr = reader.read(); if(intStr!=-1){ String aString = String.valueOf((char)intStr); String nextChar = ""; int i = 0; while((intChar = reader.read())!=-1){ nextChar = String.valueOf((char)intChar); if(string_table.contains(aString + nextChar)){ aString = aString + nextChar; }else{ i = string_table.indexOf(aString); writer.writeBitField(i); string_table.add(aString + nextChar); aString = nextChar; } // end if if(string_table.size()>MAX_VALUE){ string_table.removeAllElements(); for(int j=0; j<256; j++){ string_table.add(String.valueOf((char)j)); } } } // end while i = string_table.indexOf(aString); writer.writeBitField(i); // write a string }// end of initial is the file empty?? if writer.close(); reader.close(); } catch(IOException e){ System.out.println("ERROR: " + e); System.exit(1); } //for(int j=256; j<string_table.size() ; j++){ // System.out.println("\t"+string_table.size()); //} } // end compress } // end App |
James Little |