-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBufferedBitWriter.java
More file actions
40 lines (35 loc) · 1.09 KB
/
BufferedBitWriter.java
File metadata and controls
40 lines (35 loc) · 1.09 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
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class BufferedBitWriter {
private byte currentByte;
private byte numBitsWritten;
private int totalBytesWritten;
private BufferedOutputStream output;
public BufferedBitWriter(String pathName) throws FileNotFoundException {
currentByte = 0;
numBitsWritten = 0;
output = new BufferedOutputStream(new FileOutputStream(pathName));
}
public void writeBit(int bit) throws IOException {
if (bit != 0 && bit != 1) {
throw new IllegalArgumentException("Argument to writeBit: bit = " + bit);
}
numBitsWritten++;
currentByte |= bit << (8 - numBitsWritten);
if (numBitsWritten == 8) {
output.write(currentByte);
numBitsWritten = 0;
currentByte = 0;
totalBytesWritten++;
}
}
public void close() throws IOException {
output.write(currentByte);
output.write(numBitsWritten);
totalBytesWritten += 2;
System.out.println("Wrote " + totalBytesWritten + " bytes.");
output.close();
}
}