-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBitOutPutStream.java
73 lines (62 loc) · 1.82 KB
/
BitOutPutStream.java
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
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class BitOutPutStream extends FilterOutputStream {
private int buffer;
private int count;
public BitOutPutStream(OutputStream out) {
super(out);
buffer = 0;
count = 0;
}
public void writeBit(char bit) throws IOException {
if (!(bit == '0' || bit == '1')) {
throw new IllegalArgumentException("Input must be '0' or '1'");
}
buffer = (buffer << 1) | (bit - '0');
count++;
if (count == 8) {
out.write(buffer);
buffer = 0;
count = 0;
}
}
public void writeBit(String bits) throws IOException {
for (char bit: bits.toCharArray()) {
writeBit(bit);
}
}
@Override
public void write(int b) throws IOException {
throw new UnsupportedOperationException("Use writeBit methods to write bits");
}
@Override
public void flush() throws IOException {
if (count > 0 && count < 8) {
// Fill the remaining bits with zeros
buffer <<= (8 - count);
out.write(buffer);
buffer = 0;
count = 0;
}
super.flush();
}
@Override
public void close() throws IOException {
flush();
super.close();
}
public static void main(String[] args) {
try (BitOutPutStream bos = new BitOutPutStream(new FileOutputStream("Exercise17_17.dat"))) {
for (int i = 0; i < 10; i++) {
bos.writeBit('0');
bos.writeBit('1');
}
bos.writeBit("01010101010101011");
bos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}