-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHuffmanDemo.java
More file actions
77 lines (68 loc) · 2.08 KB
/
Copy pathHuffmanDemo.java
File metadata and controls
77 lines (68 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package Project02;
import java.io.*;
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.PriorityQueue;
/*
* CSCI232: Program 2
* Yueh-Chen Tsou
* 5/25/2019
* The program read a message from input.txt and use Huffman coding compression
* algorithm which can reduce the amount of space.
* .Accept a text message from an input file (input.txt).
* .Construct a frequency table for the message.
* .Create a Huffman tree for this message.
* .Create a code table.
* .Encode the message into binary.
* .Decode the message from binary back to the message and write into "output.txt".
*/
public class HuffmanDemo {
public static void main(String[] args) {
String myString="";
try {
Scanner fileInput = new Scanner(new File("input.txt"));
while (fileInput.hasNextLine()) {
myString = fileInput.nextLine();
}
fileInput.close();
} catch (FileNotFoundException exc) {
System.out.println("There was a problem opening the input file");
}
System.out.println("Original message: " + myString);
HuffmanTree tree = new HuffmanTree();
/*
* construct a frequency table for the message
* and create a Huffman tree for this message
*/
tree.buildTree(myString);
/*
* Create a code table
*/
Map<Character, String> huffmanCode = tree.encode();
/*
* Encode the message into binary
*/
StringBuilder sb = tree.encodeString(huffmanCode, myString);
System.out.println("\nEncoded message: " + myString);
/*
* Decode the message from binary back to the message
*/
tree.decode(sb);
/*
* print the code table, binary of encode the message,
* and the message of decode to the console
*/
tree.printCode(huffmanCode, sb);
/*
* write the message of decode into "output.txt"
*/
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write(tree.decodeStr);
writer.close();
} catch (IOException exc) {
System.out.println("There was a problem opening the input file");
}
}
}