-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncoder.java
More file actions
93 lines (77 loc) · 2.49 KB
/
Encoder.java
File metadata and controls
93 lines (77 loc) · 2.49 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.BitSet;
import java.util.HashMap;
import java.util.Map;
public class Encoder {
public static void generateCodes(BinHeapNode root, String str, HashMap<String, String> charCode)
{
if(root == null)
return;
if(root.left == null && root.right == null)
charCode.put(root.data, str);
generateCodes(root.left, str+"0",charCode);
generateCodes(root.right,str+"1",charCode);
}
public static boolean isLeaf(BinHeapNode root)
{
return !(root.left != null) && !(root.right != null) ;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
String str;
HashMap<String, Integer> huff = new HashMap<String,Integer>();
// Building Frequency Table
while ((str = in.readLine()) != null){
Integer freq = huff.get(str);
if(freq != null)
freq++;
else
freq = 1;
if(str != "" && !str.isEmpty() && str != null){
huff.put(str,freq);
}
}
in.close();
//Building Huffman Tree
CacOptHeap binHeap = new CacOptHeap();
BinHeapNode root = binHeap.buildHuffmanTree(huff);
//Generate Code-Table
HashMap<String, String> charCode = new HashMap<String, String>();
generateCodes(root, "", charCode);
PrintWriter writer = new PrintWriter("code_table.txt", "UTF-8");
for (Map.Entry<String, String> entry : charCode.entrySet()){
writer.println(entry.getKey() + " " + entry.getValue());
}
writer.close();
//Encode original input file by replacing each input value by its code
OutputStream bw1 = new FileOutputStream("encoded.bin");
BufferedReader br = new BufferedReader(new FileReader(args[0]));
String line;
int i = 0;
StringBuilder s2 = new StringBuilder();
while((line=br.readLine()) !=null && !line.equals(""))
{
if(charCode.containsKey(line))
{
s2.append(charCode.get(line));
}
}
String s = s2.toString();
while(i<s.length())
{
bw1.write((byte)Integer.parseInt(s.substring(i,i+8),2));
i = i+8;
}
bw1.close();
} catch (IOException e) {
}
}
}