forked from linkelly/COMSC-076-Projects
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chapter 17
59 lines (51 loc) · 1.77 KB
/
Chapter 17
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
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class Program2 {
public static void main(String[] args) throws Exception {
BitOutputStream output = new BitOutputStream(new File("testOutput.dat"));
output.writeBit("010000100100001001101");
output.close();
System.out.println("Done");
}
public static class BitOutputStream {
private FileOutputStream output;
private int bytePosition = 0;
private int bits; //initial bit
// programs statements
// Constructor
public BitOutputStream(File file) throws IOException {
// one statement will do the job
output = new FileOutputStream(file);
}
public void writeBit(String bitString) throws IOException {
for (int i = 0; i < bitString.length(); i++) {
writeBit(bitString.charAt(i));
}
}
public void writeBit(char bit) throws IOException {
// Program statements for this method
bits = bits << 1;
bytePosition++;
if (bit == '1') {
bits = bits | 1;
}
if (bytePosition == 8) {
output.write(bits);
bytePosition = 0; //reset position
}
}
/**
* Write the last byte and close the stream. If the last byte is not
* full, right-shift with zeros
*/
public void close() throws IOException {
// Program statements for this method
if (bytePosition > 0) {
bits = bits << 8 - bytePosition; //fills in with 0 for incompleted byte
output.write(bits);
}
output.close();
}
}
}