Friday, December 12, 2008

The Predefined Streams

The Predefined Streams

As you know, all Java programs automatically import the java.lang package. This package defines a class called System, which encapsulates several aspects of the run-time environment. For example, using some of its methods, you can obtain the current time and the settings of various properties associated with the system. System also contains three predefined stream variables, in, out, and err. These fields are declared as public and static within System. This means that they can be used by any other part of your program and without reference to a specific System object. System.out refers to the standard output stream. By default, this is the console. System.in refers to standard input, which is the keyboard by default. System.err refers to the standard error stream, which also is the console by default. However, these streams may be redirected to any compatible I/O device. System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream. These are byte streams, even though they typically are used to read and write characters from and to the console. As you will see, you can wrap these within character-based streams, if desired. The preceding Posts have been using System.out in their examples. You can use System.err in much the same way. As explained in the next section, use of System.in is a little more complicated.

 

Reading Console Input

In Java 1.0, the only way to perform console input was to use a byte stream, and older code that uses this approach persists. Today, using a byte stream to read console input is still technically possible, but doing so may require the use of a deprecated method, and this approach is not recommended. The preferred method of reading console input for Java 2 is to use a character-oriented stream, which makes your program easier to internationalize and maintain.

 

Java does not have a generalized console input method that parallels the standard C function scanf( ) or C++ input operators. In Java, console input is accomplished by reading from System.in. To obtain a character-based stream that is attached to the console, you wrap System.in in a

BufferedReader object, to create a character stream. BuffereredReader supports a buffered input stream. Its most commonly used constructor is shown here:

 

BufferedReader(Reader inputReader)

 

Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor:

 

InputStreamReader(InputStream inputStream) Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard:

 

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

 

After this statement executes, br is a character-based stream that is linked to the console through System.in.

 

Reading Characters

To read a character from a BufferedReader, use read( ). The version of read( ) that we will be using is int read( ) throws IOException Each time that read( ) is called, it reads a character from the input stream and returns it as an in eger value. It returns –1 when the end of the stream is encountered. As you can see, it can throw an IOException. The following program demonstrates read( ) by reading characters from the console

until the user types a "q":

 

// Use a BufferedReader to read characters from the console.

import java.io.*;

class BRRead {

public static void main(String args[])

throws IOException

{

char c;

BufferedReader br = new

BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter characters, 'q' to quit.");

 

// read characters

do {

c = (char) br.read();

System.out.println(c);

} while(c != 'q');

}

}

 

Here is a sample run:

Enter characters, 'q' to quit.

123abcq

1

2

3

a

b

c

q

 

This output may look a little different from what you expected, because System.in is line buffered, by default. This means that no input is actually passed to the program until you press ENTER. As you can guess, this does not make read( ) particularly valuable for interactive, console input.

 

Reading Strings To read a string from the keyboard, use the version of readLine( ) that is a member of  the BufferedReader class. Its general form is shown here:

 

String readLine( ) throws IOException

 

As you can see, it returns a String object. The following program demonstrates BufferedReader and the readLine( ) method;

 

The program reads and displays lines of text until you enter the word "stop":

 

// Read a string from console using a BufferedReader.

import java.io.*;

class BRReadLines {

320  

public static void main(String args[])

throws IOException

{

// create a BufferedReader using System.in

BufferedReader br = new BufferedReader(new

InputStreamReader(System.in));

String str;

System.out.println("Enter lines of text.");

System.out.println("Enter 'stop' to quit.");

do {

str = br.readLine();

System.out.println(str);

} while(!str.equals("stop"));

}

}

 

The next example creates a tiny text editor. It creates an array of String objects and then reads in lines of text, storing each line in the array. It will read up to 100 lines or until you enter "stop". It uses a BufferedReader to read from the console.

 

// A tiny editor.

import java.io.*;

class TinyEdit {

public static void main(String args[])

throws IOException

{

// create a BufferedReader using System.in

BufferedReader br = new BufferedReader(new

 

InputStreamReader(System.in));

String str[] = new String[100];

System.out.println("Enter lines of text.");

System.out.println("Enter 'stop' to quit.");

for(int i=0; i<100; i++) {

str[i] = br.readLine();

if(str[i].equals("stop")) break;

}

System.out.println("\nHere is your file:");

// display the lines

for(int i=0; i<100; i++) {

if(str[i].equals("stop")) break;

System.out.println(str[i]);

}

}

}

 

Here is a sample run:

Enter lines of text.

Enter 'stop' to quit.

This is line one.

This is line two.

Java makes working with strings easy.

Just create String objects.

stop

Here is your file:

This is line one.

This is line two.

Java makes working with strings easy.

Just create String objects.

Writing Console Output

 

Console output is most easily accomplished with print( ) and println( ), described earlier, which are used in most of the examples in this book. These methods are defined by the class PrintStream (which is the type of the object referenced by System.out).

 

Even though System.out is a byte stream, using it for simple program output is still acceptable. However, a character-based alternative is described in the next section. Because PrintStream is an output stream derived from OutputStream, it also implements the low-level method write( ). Thus, write( ) can be used to write to the console. The simplest form of write( ) defined by PrintStream is shown here:

 

void write(int byteval)

 

This method writes to the stream the byte specified by byteval. Although byteval is declared as an integer, only the low-order eight bits are written. Here is a short example that uses write( ) to output the character "A" followed by a newline to the screen:

 

// Demonstrate System.out.write().

class WriteDemo {

public static void main(String args[]) {

int b;

b = 'A';

System.out.write(b);

System.out.write('\n');

}

}

 

You will not often use write( ) to perform console output (although doing so might be useful in some situations), because print( ) and println( ) are substantially easier to use.

No comments: