package huffman; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class Main { // for the compressed output file static FileOutputStream fos; // the Huffman code for each byte // position 256 is for "end of file" symbol static String[] codes = new String[257]; // the bytes from the input file static byte[] bytesArray; // the following used to pack bits into bytes static int bitsindex = 0; static int partialByte = 0; static int[] powers = {128, 64, 32, 16, 8, 4, 2, 1}; public static void main(String[] args) throws IOException { File file = new File("sample.txt"); bytesArray = new byte[(int) file.length()]; try (FileInputStream fis = new FileInputStream(file);) { fis.read(bytesArray); fis.close(); fos = new FileOutputStream("compressed.bin"); } int [] freq = new int[257]; //byte array to count the frequency of each byte for (int i = 0; i < bytesArray.length; i++) { int b = bytesArray[i]; //bytes starting with a 1 are interpreted as negative //The following trick fixes that freq[b & 0xFF]++; } freq[256]=1; //for eof int count = 0; for (int i = 0; i < 257; i++) { if (freq[i]>0) { count++; } } // if byte b is the ith byte with positive frequency, // values[i] is the value of byte b // posFreq[i] is the frequency of b int[] posFreq = new int[count]; int[] values = new int[count]; int index = 0; // initialize values and posFreq arrays for (int i = 0; i < 257; i++) { if (freq[i]>0) { posFreq[index]=freq[i]; values[index++]= i; } } int n = posFreq.length; System.out.println(n); Node[] q = new Node[n+1]; // make n trees that are actually n leaves to be stored in a heap for (int i=1; i<=n; i++) q[i]=new Node(null, null, posFreq[i-1], values[i-1]); Heap h = new Heap(q, n); h.makeHeap(); for (int i=1; i