-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhdec9169.java
More file actions
102 lines (87 loc) · 1.97 KB
/
hdec9169.java
File metadata and controls
102 lines (87 loc) · 1.97 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
//Kaushil Ruparelia CS610 9169 prp
import java.io.File;
/**
* @author kaushilruparelia
*
*/
public class hdec9169 {
private static Read reader;
private static Write writer;
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//Read the file path from arguments.
if (args.length != 1) {
System.out.println("Please enter a valid filename.");
return;
}
String filename = args[0];
reader = new Read(filename);
writer = new Write(filename.substring(0, filename.length()-4));
//Set up huffman codes
CharacterCount root = decode();
printHeap(root);
//Read the length
try {
int lengthOfFile = reader.readInt();
for (int i = 0; i < lengthOfFile; i++) {
CharacterCount node = root;
while(node.isNode) {
boolean bit = reader.readBit();
if (bit) {
node = node.right;
}
else {
node = node.left;
}
}
writer.write(node.ch);
}
reader.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
writer.close();
// Erase the file
eraseFile(filename);
}
public static CharacterCount decode() {
boolean isNode;
try {
isNode = reader.readBit();
if (isNode) {
CharacterCount left = decode();
CharacterCount right = decode();
return new CharacterCount(-1, right, left);
}
else {
return new CharacterCount(reader.readChar(), -1);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
public static void printHeap(CharacterCount character) {
if (character.isNode) {
if (character.right != null) {
printHeap(character.right);
}
else {
System.out.println("Right found null");
}
if (character.left != null) {
printHeap(character.left);
}
else {
System.out.println("Left found null");
}
}
}
public static void eraseFile(String filename) {
File file = new File(filename);
file.delete();
}
}