Compress.java |
| package zzhao_ex9; import java.util.*; import java.io.*; public class Compress{ public static void main(String[] args){ Compress tester=new Compress(); String inputfilename = ""; String outputfilename = ""; try{ if (args.length == 1){//ARGS="test" inputfilename = args[0]; }else{ BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); inputfilename ="test"; PrintWriter output= new PrintWriter(new BufferedWriter(new FileWriter(inputfilename))); //BufferedWriter output = new BufferedWriter(new FileWriter(new File("test"))); String str=""; while((str=input.readLine())!=null){ output.print(str); } } outputfilename = inputfilename + ".LZW"; tester.compress(inputfilename, outputfilename); }catch(IOException e){System.out.println("Error: " + e);} }//main public void compress(String inputfilename, String outputfilename)throws IOException{ Vector string_table = new Vector(); int MAX_SIZE=4000; //initialize the first 255 characters for(int i=0; i<256; i++) string_table.add(String.valueOf((char)i)); int next_code = 256, intStr=0, intChar=0; BufferedInputStream breader = new BufferedInputStream(new FileInputStream(inputfilename)); BufferedOutputStream outBuf = new BufferedOutputStream(new FileOutputStream(outputfilename)); BitStreamOutputStream bwriter = new BitStreamOutputStream(outBuf, 12); intStr = breader.read(); String aString= String.valueOf((char)intStr); while((intChar = breader.read())!=-1){ String nextChar= String.valueOf((char)intChar); if(string_table.contains(aString + nextChar)){ aString = aString + nextChar; }else{ int i=string_table.indexOf(aString); bwriter.writeBitField(i); string_table.add(aString + nextChar); aString = nextChar; } if(string_table.size()>MAX_SIZE){ string_table.removeAllElements(); for(int j=0; j<256; j++) string_table.add(String.valueOf((char)j)); } }// end while int i=string_table.indexOf(aString); bwriter.writeBitField(i);//write aString //if(string_table.size()>MAX_SIZE){ //string_table.removeAllElements(); //for(int j=0; j<256; j++) //string_table.add(String.valueOf((char)j)); //} bwriter.close(); breader.close(); //for testing only-table ok //for(int i=0; i<string_table.size(); i++) //if(i>255) //System.out.println(" in hashtable: " // + i + " " + (String)string_table.elementAt(i)); }// compress } |
James Little |