Java Reference
In-Depth Information
number is written and the remaining three bytes are ignored. (This is the effect of casting
an
int
to a
byte
.)
On rare occasions, you may find a buggy third-party class that does
something different when writing a value outside the range 0-255—
for instance, throwing an
IllegalArgumentException
or always writ‐
ing 255—so it's best to avoid writing
int
s outside the range 0-255 if
possible.
For example, the character-generator protocol defines a server that sends out ASCII
text. The most popular variation of this protocol sends 72-character lines containing
printable ASCII characters. (The printable ASCII characters are those between 33 and
126 inclusive that exclude the various whitespace and control characters.) The first line
contains characters 33 through 104, sorted. The second line contains characters 34
through 105. The third line contains characters 35 through 106. This continues through
line 29, which contains characters 55 through 126. At that point, the characters wrap
around so that line 30 contains characters 56 through 126 followed by character 33
again. Lines are terminated with a carriage return (ASCII 13) and a linefeed (ASCII 10).
The output looks like this:
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefgh
"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghi
#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghij
$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijk
%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijkl
&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklm
'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmn
Because ASCII is a 7-bit character set, each character is sent as a single byte. Conse‐
quently, this protocol is straightforward to implement using the basic
write()
methods,
as the next code fragment demonstrates:
public
static
void
generateCharacters
(
OutputStream
out
)
throws
IOException
{
int
firstPrintableCharacter
=
33
;
int
numberOfPrintableCharacters
=
94
;
int
numberOfCharactersPerLine
=
72
;
int
start
=
firstPrintableCharacter
;
while
(
true
)
{
/* infinite loop */
for
(
int
i
=
start
;
i
<
start
+
numberOfCharactersPerLine
;
i
++)
{
out
.
write
((
(
i
-
firstPrintableCharacter
)
%
numberOfPrintableCharacters
)
+
firstPrintableCharacter
);
}
out
.
write
(
'\r'
);
// carriage return