-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoder.java
More file actions
117 lines (99 loc) · 2.82 KB
/
encoder.java
File metadata and controls
117 lines (99 loc) · 2.82 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Set;
public class encoder {
public Node build_tree_using_fourway_heap(String filepath)
{
FourwayHeap fh = new FourwayHeap();
HashMap<Integer,Integer> k = fh.frequencyTable(filepath);
Set<Integer> keySet = k.keySet();
for (int i : keySet)
{
Node x = new Node(i,k.get(i));
x.isLeaf=true;
fh.insert(x);
}
while (fh.size()>1)
{
Node A = fh.deleteMin();
Node B = fh.deleteMin();
Node C = new Node(A,B);
C.left = A;
C.right = B;
C.isLeaf=false;
fh.insert(C);
}
return fh.deleteMin();
}
public static void main(String[] args) throws FileNotFoundException, IOException
{
String filepath="";
if(args.length>0)
{
filepath = args[0];
}
else
{
System.exit(0);
}
encoder a = new encoder();
Node x =a.build_tree_using_fourway_heap(filepath);
HuffmanTree h = new HuffmanTree(x);
h.printPreorder(h.root,new String());
HashMap<Integer, String> k = h.hashy;
PrintWriter out = null;
try
{
out=new PrintWriter("code_table.txt");
for ( int i : k.keySet())
{
out.println(i+" "+ String.valueOf(k.get(i)));
}
}
catch(Exception e)
{}
finally
{
out.close();
}
try {
String outfilepath = "encoded.bin";
BufferedReader encode = new BufferedReader(new FileReader(filepath));
FileOutputStream encodingwrite = new FileOutputStream(outfilepath);
String draw;
int j;
String s=new String();
while ((draw = encode.readLine()) != null && !draw.isEmpty()) {
draw = draw.trim();
j=Integer.valueOf(draw);
s=s+k.get(j);
if(s.length() % 8 == 0){
for (int x1 = 0; x1 < s.length(); x1 += 8) {
String bS = s.substring(x1, x1 + 8);
int pByte = Integer.parseInt(bS, 2);
encodingwrite.write(pByte);
}
s = "";
}
}
while (s.length() % 8 != 0)
s += "0";
for (int x1 = 0; x1 < s.length(); x1 += 8) {
String bS = s.substring(x1, x1 + 8);
int pbyte = Integer.parseInt(bS, 2);
encodingwrite.write(pbyte);
}
encode.close();
encodingwrite.close();
}
catch(Exception E)
{
System.out.println("Error");
}
}
}