Using Readers and Writers

   

Now it's time to talk about the character stream classes that are present in the java.io package. If you remember from the previous discussion, these are used for 16-bit Unicode characters . The abstract base classes of all the Reader and Writer classes are, not sur prisingly, java.io.Reader and java.io.Writer.

These classes have the default behavior to read and write 16-bit character streams. There are similarities between the types of subclasses available underneath the byte stream super class and the subclasses available under the character stream super class. So, you should be able to do exactly the same types of things with character streams that you can do with byte streams. With character streams, however, you will notice new methods to make dealing with String objects much easier than the byte streams.

Using BufferedReader and BufferedWriter

The BufferedReader and BufferedWriter classes provide behavior for buffering of data for better efficiency. These classes are more examples of stream classes that are constructed using other stream classes. Here's a code fragment using BufferedWriter that wraps or "decorates" a FileWriter instance. Then a PrintWriter wraps the BufferedWriter for more convenient methods:

 PrintWriter out = null; out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out"))); 

Using the LineNumberReader

The LineNumberReader class is used to keep track of the line number as it reads in character data. A line is terminated by a linefeed ( \ n ), a carriage return ( \ r ), or a carriage return followed by a linefeed.

The LineNumberReader enables you to track the current line number of an input stream. As usual, you create a LineNumberReader by passing it the input stream you want it to filter:

 public LineNumberReader(new InputStreamReader(InputStream inStream)) 

The getLineNumber method returns the current line number in the input stream:

 public int getLineNumber() 

By default, the lines are numbered starting at 0. The line number is incremented every time an entire line has been read. You can set the current line number with the setLineNumber method:

 public void setLineNumber(int newLineNumber) 

Listing 21.3 shows a program that prints the contents of standard input along with the current line number.

Listing 21.3 Source Code for PrintLines.java
 import java.io.*; // This class reads lines from standard input (System.in) and // prints each line along with its line number. public class PrintLines extends Object {   public static void main(String[] args)   {     // Set up a line number input filter to count the line numbers     LineNumberReader lineCounter = new LineNumberReader( new InputStreamReader( System.in graphics/ccc.gif ) );     String nextLine = null;     System.out.println( "Type any text and press return. Type 'exit'to quit the program." graphics/ccc.gif );     try     {       // Keep going until exit is typed       while ( (nextLine = lineCounter.readLine()).indexOf( "exit") == -1 )       {         // If readLine returns null, you've hit the end of the file         if (nextLine == null) break;         // Print out the current line number followed by the line         System.out.print(lineCounter.getLineNumber());         System.out.print(": ");         System.out.println(nextLine);       }     }     catch (Exception done)     {       done.printStackTrace();     }   } } 

Using InputStreamReader and OutputStreamReader

These classes are used to bridge the gap between the byte stream classes and the character stream classes. They act as sort of a middle wrapper between the two distinct sets of streams. Listing 21.4 shows an example using the System.in stream.

Listing 21.4 Source Code for InputStreamReaderExample.java
 import java.io.*; class InputStreamReaderExample {   public static void main(String args[])   {     System.out.println("Type a line of text. Type 'exit'to quit the program.");     // Create the middle stream wrapper     InputStreamReader in = new InputStreamReader( System.in );     // Create a buffered reader around the InputStreamReader     BufferedReader reader = new BufferedReader( in );     String data = null;     try     {       // Keep looping until the user hits just return       while( (data = reader.readLine()).indexOf( "exit" ) == -1 )       {         System.out.print("The line you typed was: ");         System.out.println( data );       }     }     catch ( IOException ex )     {       System.out.println( ex );     }   } } 

PrintWriter Class

You probably noticed in Listings 21.1 and 21.2 a method called println, which is not a part of the OutputStream class. To provide for more flexible output on the standard output stream, the System class derives its output-stream object from the PrintWriter class, which provides for printing values as text output. Table 21.3 lists the methods of the PrintWriter class, along with their descriptions.

Table 21.3. Basic Methods of the PrintWriter Class
Method Description
write() Writes data to the stream
flush() Flushes data from the stream
checkError() Flushes the stream, returning errors that occurred
print() Prints data in text form
println() Prints a line of data (followed by a newline character) in text form
close() Closes the stream

As with many of the methods included in the stream classes, the write, print, and println methods are overloaded many times and come in several versions. The write method can write Strings, partial Strings, single chars, or whole char arrays, whereas the print and println methods can display almost any type of data onscreen. The various method signatures look like this:

 void write(int c) void write(char c[], int off, int len) void write(String s) void write(String s,int off,int len) void print(Object obj) void print(String s) void print(char s[]) void print(char c) void print(int i) void print(long l) void print(float f) void print(double d) void print(boolean b) void println() void println(Object obj) void println(String s) void println(char s[]) void println(char c) void println(int i) void println(long l) void println(float f) void println(double d) void println(boolean b) 

Troubleshooting Tip

If you are not seeing an exception that you are expecting using PrintWriter or PrintStream . See "Exceptions Thrown by the PrintStream and PrintWriter Classes" in the "Troubleshooting" section at the end of the chapter.


   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net