import java.io.*; import java.util.*; import javax.swing.JFileChooser; public class Huffman { String[] myEncodings; int[] myFreqs; private TreeNode myRoot; OutputStream myOut; protected static JFileChooser ourChooser = new JFileChooser(System .getProperties().getProperty("user.dir")); public Huffman() throws FileNotFoundException{ myEncodings = new String[256]; myFreqs = new int[256]; myOut = new FileOutputStream("hopethisworks.txt"); } public void openFile() throws IOException{ int retval = ourChooser.showOpenDialog(null); if (retval == JFileChooser.APPROVE_OPTION) { File file = ourChooser.getSelectedFile(); countChunks(file); makeTree(); makeEncodings(myRoot,""); writeCounts(); doCompress(file); } } public void makeEncodings(TreeNode root, String path){ if (root == null){ return; } if (root.left == null && root.right == null){ storeChunk(root.chunk,path); } else { makeEncodings(root.left, path + "0"); makeEncodings(root.right, path + "1"); } } public void writeCounts() throws IOException{ for(int k=0; k < myFreqs.length; k++){ printCount(myFreqs[k]); } } private void printCount(int i) throws IOException { myOut.write(i); } public void doCompress(File file) throws IOException{ InputStream is = new BufferedInputStream(new FileInputStream(file)); int bits; while ((bits = is.read()) != -1) { String code = myEncodings[bits]; for(int k=0; k < code.length(); k++){ if (code.charAt(k) == '0'){ printCount(0); } else { printCount(1); } } } } private void storeChunk(int chunk, String path) { myEncodings[chunk] = path; } public void makeTree(){ PriorityQueue pq = new PriorityQueue(); for(int k=0; k < myFreqs.length; k++){ if (myFreqs[k] != 0){ pq.add(new TreeNode(k,myFreqs[k],null,null)); } } while (pq.size() > 1){ TreeNode left = pq.remove(); TreeNode right = pq.remove(); pq.add(new TreeNode(0,left.weight+right.weight, left,right)); } myRoot = pq.remove(); } private void countChunks(File file) throws IOException { InputStream is = new BufferedInputStream(new FileInputStream(file)); int bits; while ((bits = is.read()) != -1) { myFreqs[bits] += 1; } int total = 0; for(int k=0; k < myFreqs.length; k++){ if (myFreqs[k] != 0) { System.out.printf("%d %d\n",k,myFreqs[k]); total += myFreqs[k]; } } System.out.printf("\ntotal = %d\n", total); } public static void main(String[] args) throws IOException{ Huffman hf = new Huffman(); hf.openFile(); } }