Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- public class HuffmanLibrary {
- public static String readFileAsString (String filename) throws FileNotFoundException {
- Scanner sc = new Scanner( new File(filename));
- String book = "";
- while (sc.hasNextLine()){
- book+=sc.nextLine();
- book+= " "; //line breaks dont have spaces so i added them
- }
- return book;
- }
- public static HLinkedList createHlist(String filecontents){
- HLinkedList list = new HLinkedList();
- for (int i = 0; i < filecontents.length(); i++){
- list.addchar(filecontents.charAt(i)); //puts all the characters in the linked list add method
- }
- return list;
- }
- public static HLinkedList getSortedLinkedList(HLinkedList list){
- list.sort(); //the sort method is in the linked list class
- return list;
- }
- public static HTree createHuffmanTree(HLinkedList list){
- return new HTree(list); //the tree is created in the tree constructor
- }
- public static void updateCodeValues(HLinkedList list, HTree tree){
- HTreeNode r = tree.getRoot();
- codeHelper("",r,list);
- }
- private static void codeHelper(String encode, HTreeNode node, HLinkedList list){
- if(node == null)return;
- if(node.left == null && node.right==null){//recursive method for encoding each letter
- list.find(node.getchar()).code = encode;
- }
- codeHelper(encode + 0, node.left, list);
- codeHelper(encode + 1, node.right, list);
- }
- public static void Huffman_coder(String input_file, String output_file) throws Exception{
- String book = readFileAsString (input_file);//read to stri
- HLinkedList l = createHlist(book);//make Hlist
- HTree t = createHuffmanTree(l);//make the tree this changes the original hlist
- HLinkedList l2 = createHlist(book);//another hlist is made to replace it
- updateCodeValues(l2,t);
- String codebook = "";
- for (int i = 0; i < book.length(); i ++){
- codebook+=l2.find(book.charAt(i)).code;
- //codebook+=(int)(math.rand()*2) :D
- }
- BinaryFileWriter.createBinaryFile(codebook, output_file);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement