Writing Console Output

In Java, console output is written by the classes namely java.io.PrintStream and java.io.PrintWriter. We will discuss about them one-by-one.

Using PrintStream class

Console output is most easily accomplished with print( ) and println( ), 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). The PrintStream class is obtained from the FilterOutputstream class that implements a number of methods for displaying textual representations of Java primitive data types. It adds the functionality to another output streams that has the ability to print various data values conveniently. Since PrintStream is an output stream derived from OutputStream, it also implements the low-level method write(), which can be used to write to the console. The simplest form of write() defined by PrintStream is shown here:

void write(int byte);

This method writes to the stream the byte specified by byte. Although byte is declared as an integer, only the low-order eight bits are written. Consider the following code snippet for example which uses write( ) to output the character ‘X’ followed by a newline to the screen:

int a = ‘X’;
System.out.write(a);
System.out.write('\n');

Unlike other OutputStreams, a PrintStream never throws an IOException and the data is flushed to a file automatically i.e. the flush method is automatically invoked after a byte array is written. The constructor of the PrintStream class is written as:

PrintStream (java.io.OutputStream); //create a new print stream

Filing is also possible with PrintStream. The print( ) and println( ) methods of this class give the same functionality as the method of standard output stream and follow the representations with new line. The given example (FileTest10.java) demonstrates the writing operation to a file using PrintStream class.

FileTest10.java

import java.io.*;

public class FileTest10 {

public static void main(String args[]) {

FileOutputStream out;
PrintStream ps; // declare a print stream object
try {
// Create a new file output stream
out = new FileOutputStream("myps.txt");
// Connect print stream to the output stream
ps = new PrintStream(out);
ps.println("This data is written to a file.");
System.err.println("Written successfully using PrintStream!");
ps.close();
}
catch (Exception e) {
System.err.println("Error in writing to file");
}

}

}

Output of the Program:

C:\file>java File10
Written successfully using PrintStream!

This program firstly create an object “ps” of the PrintStream class the specified data is written through that object using the println( ) method.

 

Using PrintWriter class

Although using System.out to write to the console is still permissible under Java, its use is recommended mostly for debugging purposes or for sample programs, such as those found in this book. For real-world programs, the recommended method of writing to the console when using Java is through a PrintWriter stream. PrintWriter is one of the character-based classes. Using a character-based class for console output makes it easier to internationalize our program. PrintWriter defines several constructors. The one we will use is shown here:

PrintWriter(OutputStream outputStream, boolean val);

Here, outputStream is an object of type OutputStream, and val controls whether Java flushes the output stream every time a println( ) method is called. If val is true, flushing automatically takes place. If false, flushing is not automatic.

PrintWriter supports the print( ) and println( ) methods for all types including Object. Thus, we can use these methods in the same way as they have been used with System.out. If an argument is not a simple type, the PrintWriter methods call the object’s toString( ) method and then print the result.

To write to the console by using a PrintWriter, we have to specify System.out for the output stream and flush the stream after each newline. For example, this line of code creates a PrintWriter that is connected to the console output:

PrintWriter pw = new PrintWriter(System.out, true);
pw.println("Hello From Java!!");
int d = 123;
pw.println(d);
double f = 4.5e + 17;
pw.println(f);

When run, the above code snippet will output the string “Hello From Java!!” followed by the variables d and f respectively to the screen.

Like PrintStream, filing is also possible with PrintWriter. The print( ) and println( ) methods of this class give the same functionality as the method of standard output stream and follow the representations with new line. The given example demonstrates the writing operation to a file using PrintStream class.

The code of this program (FileTest10a.java) is given below:

FileTest10a.java

import java.io.*;

public class FileTest10a {

public static void main(String args[]) {
FileWriter out;
PrintWriter pw; // declare a print writer object
try {
// Create a new file output stream
out = new FileWriter("mypw.txt");

// Connect print stream to the output stream
pw = new PrintWriter(out);
pw.println("This data is written to a file.");
System.err.println("Written successfully using PrintWriter!");
pw.close();
}
catch (Exception e) {
System.err.println("Error in writing to file");
}

}

}

Output of the Program:

C:\file>java File10a
Written successfully using PrintWriter!