/** * To get next char of a stream according to a codetable. * * @param codes * the codetable * @param stream * the stream * @return * byte[] representing next char * @throws IOException */ private int getNextChar(BitString[] codes, HuffmanStreamReader stream) throws IOException{ // initialize result BitString result = new BitString(); // while contains bits while (stream.available() > 0){ // read next Bit int newBit = stream.readBit(); // if next bit equals "0" -> append false/0 to result-BitString if (newBit == 0) result.append(false); // else next bit equals "1" -> append true/1 to result-BitString else result.append(true); // for every BitString in codetable for (int i = 1 ; i < codes.length ; i++){ // check if matching BitString is found and break for-loop if yes if (result.equals(codes[i])){ return i; } } } // end of stream reached and no char found throw new InvalidCharacterException(); } /** * 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 stream = new HuffmanStreamReader( new FileInputStream(inFilename)); table = stream.getCodeTable(); while (stream.available() > 0) { out.write(getNextChar(table, stream)); } }