Java Reference
In-Depth Information
fixed encoding, namely, UTF-8. Because we want to support alternative encodings, we
convert the string to bytes explicitly.
Check description length: lines 28-29
We are going to use an explicit length encoding for the string, with a single byte giving
the length. The biggest value that byte can contain is 255 bytes, so the length of the
encoded string must not exceed 255 bytes. If it does, we throw an exception.
Write encoded string: lines 30-31
Write the length of the encoded string, followed by the bytes in the buffer.
Flush output stream, return bytes: line 32
Ensure that all bytes are flushed from the DataOutputStream to the underlying byte
buffer.
ItemQuoteDecoderBin implements the corresponding decoder function.
ItemQuoteDecoderBin.java
0 import java.io.*; // for ByteArrayInputStream
1 import java.net.*; // for DatagramPacket
2
3 public class ItemQuoteDecoderBin implements ItemQuoteDecoder, ItemQuoteBinConst {
4
5
private String encoding; // Character encoding
6
7
public ItemQuoteDecoderBin() {
8
encoding = DEFAULT_ENCODING;
9
}
10
11
public ItemQuoteDecoderBin(String encoding) {
12
this.encoding = encoding;
13
}
14
15
public ItemQuote decode(InputStream wire) throws IOException {
16
boolean discounted, inStock;
17
DataInputStream src = new DataInputStream(wire);
18
long itemNumber = src.readLong();
19
int quantity = src.readInt();
20
int unitPrice = src.readInt();
21
byte flags = src.readByte();
22
int stringLength = src.read(); // Returns an unsigned byte as an int
23
if (stringLength == −1)
24
throw new EOFException();
25
byte[] stringBuf = new byte[stringLength];
26
src.readFully(stringBuf);
27
String itemDesc = new String(stringBuf,encoding);
28
return new ItemQuote(itemNumber,itemDesc, quantity, unitPrice,
29
((flags & DISCOUNT_FLAG) == DISCOUNT_FLAG),
30
((flags & IN_STOCK_FLAG) == IN_STOCK_FLAG));
31
}
Search WWH ::




Custom Search