Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.io.IOException;
- import java.util.ArrayList;
- public class Huff
- {
- File file;
- BufferedReader reader;
- BitInputStream inputStream;
- BitOutputStream outputStream;
- PriorityQueue queue;
- String string = "";
- char[] tokens;
- ArrayList<TreeNode> array = new ArrayList<TreeNode>();
- public Huff(String file)
- {
- this(new File(file));
- }
- public Huff(File file)
- {
- this.file = file;
- }
- public void read()
- {
- try {
- reader = new BufferedReader(new FileReader(file));
- while(reader.ready())
- {
- string += reader.readLine();
- }
- tokens = string.toCharArray();
- reader.close();
- }
- catch(Exception e)
- {
- e.printStackTrace();//this needs to be perfected with more catches.
- return;
- }
- boolean toAdd = true;
- for(int i = 0; i < tokens.length; i++) {
- for(int a = 0; a < array.size(); a++) {
- if(tokens[i] == (Character)(array.get(a).getValue())) {
- array.get(a).setWeight(array.get(a).getWeight() + 1);
- toAdd = false;
- break;
- }
- }
- if(toAdd) {
- array.add(new TreeNode(tokens[i], 1));
- }
- toAdd = true;
- }
- queue = new PriorityQueue(array);
- TreeNode c1;
- TreeNode c2;
- TreeNode c3;
- while (queue.size() > 1) {
- c1 = (TreeNode)queue.remove();
- c2 = (TreeNode)queue.remove();
- c3 = new TreeNode(c1.getWeight() + c2.getWeight(), c1.getWeight() + c2.getWeight(), c1, c2);
- queue.add(c3);
- }
- }
- public static void main(String[] args) {
- Huff p = new Huff("test.txt");
- p.read();
- }
- }
Add Comment
Please, Sign In to add comment