Open In App

Java.io.Printstream Class in Java | Set 1

A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the checkError method. Optionally, a PrintStream can be created so as to flush automatically.
All characters printed by a PrintStream are converted into bytes using the platform’s default character encoding. The PrintWriter class should be used in situations that require writing characters rather than bytes.

Class declaration



public class PrintStream
  extends FilterOutputStream
    implements Appendable, Closeable

Field

 protected OutputStream out:This is the output stream to be filtered. 

Constructors and Description



Methods:




import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Locale;
//Java program to demonstrate PrintStream methods
class Printstream
{
    public static void main(String args[]) throws FileNotFoundException
    {
        FileOutputStream fout=new FileOutputStream("file.txt");
          
        //creating Printstream obj
        PrintStream out=new PrintStream(fout);
        String s="First";
  
        //writing to file.txt
        char c[]={'G','E','E','K'};
          
        //illustrating print(boolean b) method
        out.print(true);
          
        //illustrating print(int i) method
        out.print(1);
          
        //illustrating print(float f) method
        out.print(4.533f);
          
        //illustrating print(String s) method
        out.print("GeeksforGeeks");
        out.println();
          
        //illustrating print(Object Obj) method
        out.print(fout);
        out.println();
          
        //illustrating append(CharSequence csq) method
        out.append("Geek");
        out.println();
          
        //illustrating checkError() method
        out.println(out.checkError());
          
        //illustrating format() method
        out.format(Locale.UK, "Welcome to my %s program", s);
          
        //illustrating flush method
        out.flush();
          
        //illustrating close method
        out.close();
    }
}

Note: The output might not be visible on online IDE as it is not able to read the file.
Output:

true14.533GeeksforGeeks
java.io.FileOutputStream@1540e19dGeek
false
Welcome to my First program

Next Article: Java.io.Printstream Class in Java | Set 2


Article Tags :