Java Reference
In-Depth Information
10
public ItemQuoteEncoderBin(String encoding) {
11
this.encoding = encoding;
12
}
13
14
public byte[] encode(ItemQuote item) throws Exception {
15
16
ByteArrayOutputStream buf = new ByteArrayOutputStream();
17
DataOutputStream out = new DataOutputStream(buf);
18
out.writeLong(item.itemNumber);
19
out.writeInt(item.quantity);
20
out.writeInt(item.unitPrice);
21
byte flags = 0;
22
if (item.discounted)
23
flags |= DISCOUNT_FLAG;
24
if (item.inStock)
25
flags |= IN_STOCK_FLAG;
26
out.writeByte(flags);
27
byte[] encodedDesc = item.itemDescription.getBytes(encoding);
28
if (encodedDesc.length > MAX_DESC_LEN)
29
throw new IOException("Item Description exceeds encoded length limit");
30
out.writeByte(encodedDesc.length);
31
out.write(encodedDesc);
32
out.flush();
33
return buf.toByteArray();
34
}
35 }
ItemQuoteEncoderBin.java
1. Constants, variables, and constructors: lines 4-12
2. encode() : lines 14-34
Set up Output: lines 16-17
Again, a ByteArrayOutputStream collects the bytes of the encoded message. Encapsu-
lating the ByteArrayOutputStream in a DataOutputStream allows use of its methods for
writing binary integers.
Write integers: lines 18-20
The writeLong() method writes the long 's 8 bytes to the stream in big-endian order.
Similarly, writeInt() outputs 4 bytes.
Write booleans as flags: lines 21-26
Encode each boolean using a single bit in a flag byte. Initialize the flag byte to 0, then
set the appropriate bits to 1, if either discounted or inStock is true. (The bits are defined
in the ItemQuoteBinConst interface to be the most and least significant bits of the byte,
respectively.) Write the byte to the stream.
Convert description string to bytes: line 27
Although DataOutputStream provides methods for writing String s, it supports only one
Search WWH ::




Custom Search