-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitOutputStream.java
More file actions
75 lines (67 loc) · 2.24 KB
/
BitOutputStream.java
File metadata and controls
75 lines (67 loc) · 2.24 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
//The BitOutputStream and BitInputStream classes provide the ability to
//write and read individual bits to a file in a compact form. One major
//limitation of this approach is that the resulting file will always have
//a number of bits that is a multiple of 8. In effect, whatever bits are
//output to the file are padded at the end with 0's to make the total
//number of bits a multiple of 8.
//
//BitOutputStream has the following public methods:
// public BitOutputStream(String file)
// opens an output stream with the given file name
// public void writeBit(int bit)
// write given bit to output
// public void close()
// closes the output, flushing the internal buffer
import java.io.*;
public class BitOutputStream {
private FileOutputStream output;
private int digits; // a buffer used to build up next set of digits
private int numDigits; // how many digits are currently in the buffer
private static final int BYTE_SIZE = 8; // digits per byte
// pre : given file name is legal
// post: creates a BitOutputStream sending output to the file
public BitOutputStream(String file) {
try {
output = new FileOutputStream(file);
} catch (IOException e) {
throw new RuntimeException(e.toString());
}
digits = numDigits = 0;
}
// post: writes given bit to output
public void writeBit(int bit) {
if (bit < 0 || bit > 1)
throw new IllegalArgumentException("Illegal bit: " + bit);
digits += bit << numDigits;
numDigits++;
if (numDigits == BYTE_SIZE)
flush();
}
// post: Flushes the buffer. If numDigits < BYTE_SIZE, this will
// effectively pad the output with extra 0's, so this should
// be called only when numDigits == BYTE_SIZE or when we are
// closing the output.
private void flush() {
try {
output.write(digits);
} catch (IOException e) {
throw new RuntimeException(e.toString());
}
digits = 0;
numDigits = 0;
}
// post: output is closed
public void close() {
if (numDigits > 0)
flush();
try {
output.close();
} catch (IOException e) {
throw new RuntimeException(e.toString());
}
}
// included to ensure that the stream is closed
protected void finalize() {
close();
}
}