Home Java Example Java Io Working with PrintStream
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Working with PrintStream

Advertisement
The PrintStream class is obtained from the FilterOutputstream class that implements a number of methods for displaying textual representations of Java primitive data types.

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");
  ps.close();
  }
  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

C:\nisha>

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

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 7, 2008

Ask Questions?    Discuss: Working with PrintStream   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
nisha
September 6, 2011
nisha

nisha
veronica
December 16, 2011
Developing Concurrent distributed systems

It seems to be difficult for me to understand code and execute desired output
DMCA.com