/** * This method performs the compression 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 compression. First write the used code * table into the file as described in the task, followed by the compressd * data. You may use the class HuffmanStreamWriter here. This class * proviedes methods to write down the table and for writing BitStrings into * the OutputStream. * * @param inFilename * the file to compress * @param out * outputStram to wirte the results * @throws IOException */ public void compress(String inFilename, OutputStream out) throws IOException { PriorityQueue<HuffmanTree> queue = new PriorityQueue<HuffmanTree>(); FileInputStream stream = new FileInputStream(inFilename); int[] count = getOccurence(stream); count[0] = 1; for (int i = 0; i < 256; i++) { HuffmanTree temp = new HuffmanTree((char) i, count[i]); queue.add(temp); } while (queue.size() > 1) { HuffmanTree first = queue.poll(); HuffmanTree second = queue.poll(); HuffmanTree tempTree = new HuffmanTree(first, second); queue.offer(tempTree); } HuffmanTree result = queue.poll(); table = result.encode(new BitString[256], new BitString());[...] }-------------------------------------------------------------------------------------/** * To count the occurence of every char in a stream. * * @param stream * stream to count chars in * @return int-array containing amount for every char (index = ascii-code) * @throws IOException */ private int[] getOccurence(InputStream stream) throws IOException { int[] result = new int[256]; while (stream.available() > 0) { int newChar = stream.read(); if (newChar == (char) 0) throw new InvalidCharacterException(); else result[newChar] = result[newChar] + 1; } return result; }