Java Reference
In-Depth Information
26
out.write('\n');
27
out.flush();
28
if (buf.size() > MAX_WIRE_LENGTH)
29
throw new IOException("Encoded length too long");
30
return buf.toByteArray();
31
}
32
}
ItemQuoteEncoderText.java
1.
Constructors:
lines 6-12
If no encoding is explicitly specified, we use the default encoding specified in the constant
interface.
2.
encode()
method:
lines 14-31
Create an output buffer:
lines 15-16
A
ByteArrayOutputStream
collects the bytes to be returned. Wrapping it in an
Out−
putWriter
allows us to take advantage of the latter's methods for converting strings
to bytes.
Write the first integer, followed by a space delimiter:
line 17
Check for delimiter:
lines 18-19
Make sure that the field delimiter is not contained in the field itself. If it is, throw an
exception.
Output
itemDescription
and other integers:
lines 20-21
Write the flag characters if the booleans are true:
lines 22-25
Write the delimiter for the flag field:
line 26
Flush the output stream:
lines 27-29
Flush everything to the underlying stream, and call
size()
to check that the resulting
byte sequence is not too long. The length restriction allows the receiver to know how
big a buffer is needed to receive into a
DatagramPacket
. (For stream communication,
this is not necessary, but it is still convenient.)
Return the byte array from the output stream:
line 30
The decoding class
ItemQuoteDecoderText
simply inverts the encoding process.
ItemQuoteDecoderText.java
0
import java.io.*; // for InputStream, ByteArrayInputStream, and IOException
1
import java.net.*; // for DatagramPacket
2
3
public class ItemQuoteDecoderText implements ItemQuoteDecoder, ItemQuoteTextConst {
4
5
private String encoding; // Character encoding
Search WWH ::
Custom Search