[an error occurred while processing this directive]

Working with PrintStream


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. Unlike other output streams, 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 out);   //create a new print stream

The print( ) and Println( ) methods of this class give the same functionality as the method of standard output stream and follow the representations with newline.

The given example demonstrate the writing operation to a file using PrintStream class.

import java.io.*;

class PrintStreamDemo {  
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("myfile.txt");

                        // Connect print stream to the output stream
                        ps = new PrintStream(out);
                        ps.println ("This data is written to a file:");
            System.err.println ("Write successfully");
                catch (Exception e){
                        System.err.println ("Error in writing to file");

Output of the Program:

C:\nisha>javac PrintStreamDemo.java

C:\nisha>java PrintStreamDemo
Write successfully


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

Download this Program


[an error occurred while processing this directive]