Java Reference
In-Depth Information
figure 4.21
A program that
demonstrates the
wrapping of streams
and readers
1
import java.io.InputStreamReader;
2
import java.io.BufferedReader;
3
import java.io.IOException;
4
import java.util.Scanner;
5
import java.util.NoSuchElementException;
6
7
class MaxTest
8
{
9
public static void main( String [ ] args )
10
{
11
BufferedReader in = new BufferedReader( new
12
InputStreamReader( System.in ) );
13
14
System.out.println( "Enter 2 ints on one line: " );
15
try
16
{
17
String oneLine = in.readLine( );
18
if( oneLine == null )
19
return;
20
Scanner str = new Scanner( oneLine );
21
22
int x = str.nextInt( );
23
int y = str.nextInt( );
24
25
System.out.println( "Max: " + Math.max( x, y ) );
26
}
27
catch( IOException e )
28
{ System.err.println( "Unexpected I/O error" ); }
29
catch( NoSuchElementException e )
30
{ System.err.println( "Error: need two ints" ); }
31
}
32
}
The wrapping idea is an example of a commonly used Java design pat-
tern, which we will see again in Section 4.6.2.
Similar to the
BufferedReader
is the
PrintWriter
, which allows us to do
println
operations.
The
OutputStream
hierarchy includes several wrappers, such as
DataOutput-Stream
,
ObjectOutputStream
, and
GZIPOutputStream
.
DataOutputStream
allows us to write primitives in binary form (rather than
human-readable text form); for instance, a call to
writeInt
writes the 4 bytes
that represent a 32-bit integer. Writing data that way avoids conversions to text
form, resulting in time and (sometimes) space savings.
ObjectOutputStream
allows us to write an entire object including all its components, its compo-
nent's components, etc., to a stream. The object and all its components must
Search WWH ::
Custom Search