Advertisement
Guest User

Decoder

a guest
Jul 23rd, 2010
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.92 KB | None | 0 0
  1. import java.io.DataInputStream;
  2. import java.io.DataOutputStream;
  3. import java.io.EOFException;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7.  
  8. //Alexander Linton
  9. //I discussed this with Elisabeth Hutzel
  10.  
  11. /**
  12.  * HW9
  13.  *
  14.  * This class takes in a file and decodes the file from a Huffman encoding and
  15.  * makes an output file based on the input.
  16.  */
  17. public class Decoder
  18. {
  19.  
  20.     /**
  21.      * This method takes in a file from the command line and then decodes the
  22.      * file from a Huffman encoding in the way specified in the homework
  23.      * @param args the file
  24.      */
  25.     public static void main(String[] args) throws IOException
  26.     {
  27.         DataInputStream input = new DataInputStream(new FileInputStream(args[0]));
  28.         String filename = args[0].substring(0, (args[0].length() - 3));
  29.         DataOutputStream output = new DataOutputStream(new FileOutputStream(filename));
  30.         int[] header = new int[772];
  31.         int Iindex = 0;
  32.         while ((input.available()>0) && (Iindex<772))
  33.         {
  34.             header[Iindex] = input.readUnsignedByte();
  35.             Iindex++;
  36.         }
  37.         int size =  header[0]<<24 | header[1]<<16 | header[2]<<8 | header[3];
  38.         int[] frequencies = new int[256];
  39.         for(int i = 0; i < 256; i++)
  40.         {
  41.             frequencies[i] = header[3*i +4]<<16 | header[3*i + 5]<<8 | header[3*i + 6];
  42.         }
  43.         HuffmanNodeType node = HuffmanNode.buildHuffmanTree(frequencies);
  44.         HuffmanNodeType copy = node;
  45.         int current = input.readUnsignedByte();
  46.         int bit = 7;
  47.         while(output.size() < size && input.available() > 0)
  48.         {
  49.             while(node.getData() == null)
  50.             {
  51.                 if(((current>>>bit)&1) == 1)
  52.                     node = node.getRightChild();
  53.                 else if(((current>>>bit)&1) == 0)
  54.                     node = node.getLeftChild();
  55.                 if(bit > 0)
  56.                 {
  57.                     bit--;
  58.                 }
  59.                 else
  60.                 {
  61.                     current = input.readUnsignedByte();
  62.                     bit = 7;
  63.                 }
  64.             }
  65.             output.write(node.getData());
  66.             node = copy;
  67.         }
  68.         input.close();
  69.         output.close();
  70.     }
  71.    
  72.        
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement