Java Reference
In-Depth Information
1.
nextToken()
:
lines 4-24
Read from input stream until delimiter or end-of-stream.
Test for end-of-stream:
lines 8-10
If the input stream is already at end-of-stream, return
null
.
Create a buffer to hold the bytes of the token:
line 12
We use a
ByteArrayOutputStream
to collect the data byte by byte. The
ByteArray[Input|
Output]Stream
classes allow a byte array to be handled like a stream of bytes.
Put the last byte read into the buffer :
line 14
Get a byte array containing the input so far:
line 15
It is very inecient to create a new byte array on each iteration, but it is simple.
Check whether the delimiter is a sux of the current token:
lines 16-21
If so, create a new byte array containing the bytes read so far, minus the delimiter
sux, and return it.
Get next byte:
line 22
Return the current token on end-of-stream:
line 23
2.
endswith()
:
lines 26-35
Compare lengths:
lines 28-29
The candidate sequence must be at least as long as the delimiter to be a match.
Compare bytes, return
false
on any difference:
lines 31-33
Compare the last
delim.length
bytes of the token to the delimiter.
If no difference, return
true
:
line 34
3.4
Implementing Wire Formats in Java
To emphasize the fact that the same information can be represented “on the wire” in different
ways, we define an interface
ItemQuoteEncoder
, which has a single method that takes an
ItemQuote
instance and converts it to a
byte[ ]
that can be written to an
OutputStream
or
encapsulated in a
DatagramPacket
.
ItemQuoteEncoder.java
0
public interface ItemQuoteEncoder {
1
byte[] encode(ItemQuote item) throws Exception;
2
}
ItemQuoteEncoder.java
The specification of the corresponding decoding functionality is given by the
ItemQuot−
eDecoder
interface, which has methods for parsing messages received via streams or in
Data−
Search WWH ::
Custom Search