All pastes #593395 Raw Edit

Stuff

public java v1 · immutable
#593395 ·published 2007-06-28 09:36 UTC
rendered paste body
/**	 * This method performs the uncompression of the file inFilename. It writes	 * the results to the OutputStream out.	 * 	 * IMPORTANT: We use this method for testing your solution. Don't modify the	 * signature of this method.	 * 	 * Implement a Huffman Tree based uncompression. The used code table is	 * stored at the begin of the file. You can use the class	 * HuffmanStreamReader to get the table. This class also offers methods to	 * read a file bit by bit.	 * 	 * @param inFilename	 *            the file to uncompress	 * @param out	 *            outputStram to wirte the results	 * @throws IOException	 */	public void uncompress(String inFilename, OutputStream out)			throws IOException {		HuffmanStreamReader reader = new HuffmanStreamReader(new FileInputStream(inFilename));		table = reader.getCodeTable();		HuffmanTree tree = getHuffmanTree(table);		int bit;				while ((bit = reader.readBit()) != -1){			System.out.print(bit);			if (tree.isLeaf()){				out.write(table[tree.name].getByteArray());				System.out.println();				tree = getHuffmanTree(table);			}			else if (bit == 0){				tree = tree.left;			}			else if (bit == 1){				tree = tree.right;			}		}	}		/**	 * To create a HuffmanTree according to a codetable.	 * 	 * @param codes	 * 				the codetable	 * @return	 * 				resulting HuffmanTree	 */	private HuffmanTree getHuffmanTree(BitString[] codes){		// initialize resulting HuffmanTree		HuffmanTree result = new HuffmanTree();		// for each entry in codetable		for (int i = 0 ; i < codes.length ; i++){			// initialize iteration-variable			HuffmanTree actTree = result;			// if code exists			if (codes[i] != null){				// get String-representation of code				String newChar = codes[i].toString();				// for each char of String-representation				for (int j = 0 ; j < codes[i].getLength() ; j++){					// check if subtrees exist and create them if not					if (actTree.isEmpty()){						actTree.left = new HuffmanTree();						actTree.right = new HuffmanTree();					}					// if char is "0" -> go on with left subtree					if (newChar.charAt(j) == 0)						actTree = actTree.left;					// otherwise char is "1" -> go on with right subtree					else						actTree = actTree.right;				}				// new leaf reached -> store char represented by code (= path in tree)				actTree.name = i;			}		}		// return new built HuffmanTree		return result;	}