Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package huffman;
- import java.io.*;
- import java.util.*;
- public class Huffman {
- static String[] code = new String[256];
- private static void processFile(String fileContents)
- {
- int[] frequency = new int[256]; // Frequency table of each letter
- TreeSet<Node> trees = new TreeSet<Node>(); // List containing all trees -- ORDERED!
- // Build the frequency table of each letter
- for (int i=0; i<fileContents.length(); i++)
- {
- char ch = fileContents.charAt(i);
- try {
- ++frequency[ch];
- } catch (Exception e) {
- // TODO Auto-generated catch block
- System.out.println(ch);
- }
- }
- // Build up the initial trees
- for (int i=0; i<256; i++)
- {
- if (frequency[i] > 0)
- {
- Node n = new Node((char)(i), frequency[i]);
- trees.add(n);
- }
- }
- // Huffman algoritm
- while (trees.size() > 1)
- {
- Node tree1 = (Node) trees.first();
- trees.remove(tree1);
- Node tree2 = (Node) trees.first();
- trees.remove(tree2);
- Node merged = new Node(tree1, tree2);
- trees.add(merged);
- }
- // Print the resulting tree
- if (trees.size() > 0)
- {
- Node theTree = (Node) trees.first();
- theTree.printTree(code);
- }
- else
- System.out.println("The file didn't contain useful characters.");
- }
- public static String compress(String string) {
- String comprssed = "";
- for (int i = 0; i < string.length(); i++) {
- comprssed += code[string.charAt(i)]/*+" "*/;
- }
- return comprssed;
- }
- public static void run() throws Exception{
- StringBuffer fileContents = new StringBuffer();
- FileInputStream fi = new FileInputStream(new File("text.in"));
- int line = 0;
- while ((line = fi.read()) != -1)
- fileContents.append(line).append("\n");
- processFile(fileContents.toString());
- String s = compress(fileContents.toString());
- BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream(new File("compressed.out")));
- //System.out.println(s);
- String tmp;
- for (int j = 0; j < s.length(); j+=8)
- {
- if (j + 8 < s.length()-8)
- tmp = s.substring(j, j + 8);
- else
- tmp = s.substring(j, s.length() - 1);
- int x= Integer.parseInt(tmp,2);
- System.out.println(x);
- bw.write(x);
- }
- bw.close();
- System.out.println("finish");
- }
- public static void main(String[] args) throws Exception
- {
- // StringBuffer fileContents = new StringBuffer();
- //
- // BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- //
- // String line = null;
- // while (!(line = br.readLine()).equals("0"))
- // fileContents.append(line);
- //
- // processFile(fileContents.toString());
- run();
- //System.out.println((int)'—');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement