-
Notifications
You must be signed in to change notification settings - Fork 0
/
Write.java
126 lines (108 loc) · 2.38 KB
/
Write.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
//Kaushil Ruparelia CS610 9169 prp
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Writes the data to a file.
* @author kaushilruparelia
*
*/
public class Write {
private static BufferedOutputStream outputStream;
private static int buffer;
private static int lengthOfBuffer;
public Write() {
outputStream = new BufferedOutputStream(System.out);
}
public Write(String filename) {
try {
outputStream = new BufferedOutputStream(new FileOutputStream(filename));
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
/**
* Write bit to file
* @param bit
*/
public void write(boolean bit) {
buffer <<= 1;
if (bit) buffer |= 1;
lengthOfBuffer++;
if (lengthOfBuffer == 8) writeBuffer();
}
/**
* Write char to file
* @param ch
*/
public void write(char ch) {
writeByte(ch);
}
public void write(int number) {
writeByte((number >>> 24) & 0xff);
writeByte((number >>> 16) & 0xff);
writeByte((number >>> 8) & 0xff);
writeByte((number >>> 0) & 0xff);
}
/**
* Writes the buffer to the output file.
*/
private static void writeBuffer() {
if(lengthOfBuffer == 0)
return;
//If buffer is not full, shift the bits to right and pad with 0s
if (lengthOfBuffer > 0) {
buffer<<= 8 - lengthOfBuffer;
}
try {
outputStream.write(buffer);
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
lengthOfBuffer = 0;
buffer = 0;
}
/**
* Writes a byte value
* @param myByte
*/
private void writeByte(int myByte) {
//Check if buffer is empty
if (lengthOfBuffer == 0) {
try {
outputStream.write(myByte);
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
else {
//Print bitwise
for (int i = 0; i < 8; i++) {
boolean bit = ((myByte >>> (7-i)) & 1) == 1;
write(bit);
}
}
}
/**
* Close the file write
*/
public void close() {
writeBuffer();
try {
outputStream.flush();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}