1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.imaging.common;
18
19 import java.io.IOException;
20 import java.io.OutputStream;
21 import java.nio.ByteOrder;
22
23 public class BinaryOutputStream extends OutputStream {
24 private final OutputStream os;
25
26 private ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
27 private int count;
28
29 public BinaryOutputStream(final OutputStream os, final ByteOrder byteOrder) {
30 this.byteOrder = byteOrder;
31 this.os = os;
32 }
33
34 public BinaryOutputStream(final OutputStream os) {
35 this.os = os;
36 }
37
38 protected void setByteOrder(final ByteOrder byteOrder) {
39 this.byteOrder = byteOrder;
40 }
41
42 public ByteOrder getByteOrder() {
43 return byteOrder;
44 }
45
46 @Override
47 public void write(final int i) throws IOException {
48 os.write(i);
49 count++;
50 }
51
52 @Override
53 public final void write(final byte[] bytes) throws IOException {
54 os.write(bytes, 0, bytes.length);
55 count += bytes.length;
56 }
57
58 @Override
59 public final void write(final byte[] bytes, final int offset, final int length) throws IOException {
60 os.write(bytes, offset, length);
61 count += length;
62 }
63
64 @Override
65 public void flush() throws IOException {
66 os.flush();
67 }
68
69 @Override
70 public void close() throws IOException {
71 os.close();
72 }
73
74 public int getByteCount() {
75 return count;
76 }
77
78 public final void write4Bytes(final int value) throws IOException {
79 if (byteOrder == ByteOrder.BIG_ENDIAN) {
80 write(0xff & (value >> 24));
81 write(0xff & (value >> 16));
82 write(0xff & (value >> 8));
83 write(0xff & value);
84 } else {
85 write(0xff & value);
86 write(0xff & (value >> 8));
87 write(0xff & (value >> 16));
88 write(0xff & (value >> 24));
89 }
90 }
91
92 public final void write3Bytes(final int value) throws IOException {
93 if (byteOrder == ByteOrder.BIG_ENDIAN) {
94 write(0xff & (value >> 16));
95 write(0xff & (value >> 8));
96 write(0xff & value);
97 } else {
98 write(0xff & value);
99 write(0xff & (value >> 8));
100 write(0xff & (value >> 16));
101 }
102 }
103
104 public final void write2Bytes(final int value) throws IOException {
105 if (byteOrder == ByteOrder.BIG_ENDIAN) {
106 write(0xff & (value >> 8));
107 write(0xff & value);
108 } else {
109 write(0xff & value);
110 write(0xff & (value >> 8));
111 }
112 }
113 }