Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3. public class HuffmanLibrary {
  4. public static String readFileAsString (String filename) throws FileNotFoundException {
  5. Scanner sc = new Scanner( new File(filename));
  6. String book = "";
  7. while (sc.hasNextLine()){
  8. book+=sc.nextLine();
  9. book+= " "; //line breaks dont have spaces so i added them
  10. }
  11. return book;
  12.  
  13. }
  14. public static HLinkedList createHlist(String filecontents){
  15. HLinkedList list = new HLinkedList();
  16. for (int i = 0; i < filecontents.length(); i++){
  17. list.addchar(filecontents.charAt(i)); //puts all the characters in the linked list add method
  18. }
  19. return list;
  20. }
  21. public static HLinkedList getSortedLinkedList(HLinkedList list){
  22. list.sort(); //the sort method is in the linked list class
  23. return list;
  24. }
  25. public static HTree createHuffmanTree(HLinkedList list){
  26. return new HTree(list); //the tree is created in the tree constructor
  27. }
  28. public static void updateCodeValues(HLinkedList list, HTree tree){
  29. HTreeNode r = tree.getRoot();
  30. codeHelper("",r,list);
  31. }
  32. private static void codeHelper(String encode, HTreeNode node, HLinkedList list){
  33. if(node == null)return;
  34. if(node.left == null && node.right==null){//recursive method for encoding each letter
  35. list.find(node.getchar()).code = encode;
  36. }
  37. codeHelper(encode + 0, node.left, list);
  38. codeHelper(encode + 1, node.right, list);
  39. }
  40.  
  41. public static void Huffman_coder(String input_file, String output_file) throws Exception{
  42. String book = readFileAsString (input_file);//read to stri
  43. HLinkedList l = createHlist(book);//make Hlist
  44. HTree t = createHuffmanTree(l);//make the tree this changes the original hlist
  45. HLinkedList l2 = createHlist(book);//another hlist is made to replace it
  46. updateCodeValues(l2,t);
  47. String codebook = "";
  48. for (int i = 0; i < book.length(); i ++){
  49. codebook+=l2.find(book.charAt(i)).code;
  50. //codebook+=(int)(math.rand()*2) :D
  51. }
  52. BinaryFileWriter.createBinaryFile(codebook, output_file);
  53.  
  54.  
  55. }
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement