PrintStream class :
- The PrintStream class is obtained from the FilterOutputstream class that implements a number of methods for displaying textual representations of Java primitive data types.
- 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.
Simple java program that prints hello world:
import java.io.PrintStream;
class Example
{
public static void main(String[] args)
{
PrintStream ps=new PrintStream(System.out);
ps.println("Hello World!");
}
}
Writing data on to the File:
import java.io.*;
public class PrintStreamDemo
{
public static void main(String[] args)
{
try
{
FileOutputStream out = new FileOutputStream("out.txt");
PrintStream p = new PrintStream(out);
p.println("this text will be written into out.txt after run");
System.out.println("text has been written, go and check out.txt in the current directory");
p.close();
} catch (Exception e) {}
}
}