-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileCompressor.java
More file actions
37 lines (27 loc) · 1.04 KB
/
Copy pathFileCompressor.java
File metadata and controls
37 lines (27 loc) · 1.04 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
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class FileCompressor {
public static void compress(String inputFile, String outputFile) throws Exception {
byte[] data = Files.readAllBytes(Paths.get(inputFile));
Map<Byte, Integer> freqMap = new HashMap<>();
for (byte b : data) {
freqMap.put(b, freqMap.getOrDefault(b, 0) + 1);
}
HuffmanNode root = HuffmanTree.buildTree(freqMap);
HuffmanEncoder encoder = new HuffmanEncoder();
Map<Byte, String> codes = encoder.generateCodes(root);
try (ObjectOutputStream oos =
new ObjectOutputStream(new FileOutputStream(outputFile))) {
oos.writeObject(freqMap); // metadata
BitOutputStream bos = new BitOutputStream(oos);
for (byte b : data) {
String code = codes.get(b);
for (char c : code.toCharArray()) {
bos.writeBit(c == '1' ? 1 : 0);
}
}
bos.close();
}
}
}