-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathBitOutputStream.java
More file actions
47 lines (39 loc) · 1.18 KB
/
BitOutputStream.java
File metadata and controls
47 lines (39 loc) · 1.18 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
package Huffman;
import java.io.IOException;
import java.io.OutputStream;
/* BitOutputStream using decorator pattern */
public final class BitOutputStream {
private OutputStream output;
private int currentByte;
private int numBitsInCurrentByte;
public BitOutputStream(OutputStream out) {
if (out == null) {
throw new NullPointerException("Argument is null");
}
output = out;
currentByte = 0;
numBitsInCurrentByte = 0;
}
public void write(int b) throws IOException {
if (!(b == 0 || b == 1)) {
throw new IllegalArgumentException("Argument must be 0 or 1");
}
currentByte = currentByte << 1 | b;
numBitsInCurrentByte++;
if (numBitsInCurrentByte == 8) {
output.write(currentByte);
numBitsInCurrentByte = 0;
}
}
public void write(String s) throws IOException {
for (int i = 0; i < s.length(); i++) {
write(Character.getNumericValue(s.charAt(i)));
}
}
public void close() throws IOException {
while (numBitsInCurrentByte != 0) {
write(0);
}
output.close();
}
}