Printstream class in Java

Printstream class in Java is a sub-class of FilterOutputStream class and it is used to write data as it is in the given format. It means, unlike FileOutputStream class, PrintStream class writes 97 as 97 rather than one byte. It is the most convenient class in writing binary data to another output stream. In addition to default write() methods it define new methods called print() and println(). These two methods are overloaded to print all types of java data type value including objects as it is in those formats.

public class PrintStream extends FilterOutputStream
implements Appendable, Closeable

FilterOutputStream class sub class of OutputStream class.

Java PrintStream class Constructors

Constructors to creates a new print stream, without automatic line flushing, with the specified file:-

  • public PrintStream(File file) throws FileNotFoundExceptio
  • public PrintStream(String fileName) throws FileNotFoundException

The constructors to creates a new print stream, without automatic line flushing, with the specified file and charset:-

  • public PrintStream(File file, String csn) throws FileNotFoundException, UnsupportedEncodingException
  • public PrintStream(String fileName, String csn) throws FileNotFoundException, UnsupportedEncodingException

Constructors using OutputStream

  • public PrintStream(OutputStream out):- Creates a new print stream, without automatic line flushing, with the specified OutputStream.
  • public PrintStream(OutputStream out, boolean autoFlush):- Creates a new print stream, with the specified OutputStream and line flushing.
  • public PrintStream(OutputStream out, boolean autoFlush, String encoding) throws UnsupportedEncodingException:- It Creates a new print stream, with the specified OutputStream, line flushing, and character encoding.

New constructors added in Java 10 is,

  • public PrintStream(File file, Charset charset) throws IOException
  • public PrintStream(String fileName, Charset charset) throws IOException
  • public PrintStream(OutputStream out, boolean autoFlush, Charset charset)

Java PrintStream class Methods

In PrintStream class there are many methods to write data with or without new lines, with or without formatting, and e.t.c. These methods are given below.

Print println and write methods

Overloaded forms of print() method to write data without terminating line,

  • public void print(boolean b)
  • public void print(char c)
  • public void print(int i)
  • public void print(long l)
  • public void print(float f)
  • public void print(double f)
  • public void print(char s[])
  • public void print(String s)
  • public void print(Object obj)

These methods are printing the given data as it is in the given format because internally these methods are calling the “String.valueOf()” method convert given data into String data. Then the returned string data is printing on the destination. Among these methods except print(char s[]) all other methods are calling write(String.valueOf(x) method.

public void print(int i) {
   write(String.valueOf(i));
}

Overloaded forms of println() method to write data with terminating lines,

  • public void println()
  • public void println(boolean x)
  • public void println(char x)
  • public void println(int x)
  • public void println(long x)
  • public void println(float x)
  • public void println(double x)
  • public void println(char[] x)
  • public void println(String x)
  • public void println(Object x)

The println() method is calling the newLine() method which terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ‘\n’.

Other overloaded forms of println() methods are internally calling print(-) method and newLine() method. For Example:-

public void println(int x) {
   if (getClass() == PrintStream.class) {
      writeln(String.valueOf(x));
   } else {
      synchronized (this) {
         print(x);
         newLine();
      }
   }
}

Overloaded forms of write() methods to write data:-

  • public void write(int b)
  • public void write(byte buf[], int off, int len)

Another two overloaded forms of write() method was given in Java14 version which writes all bytes from the specified byte array to this stream are:-

  • public void write(byte buf[]) throws IOException
  • public void writeBytes(byte buf[])

Note:- In PrintStream class only write(byte buf[]) method throws IOException.

Another methods

The format() method to write formatted string to the output stream using the specified format string and arguments:-

  • public PrintStream format(String format, Object ... args)
  • public PrintStream format(Locale l, String format, Object ... args)

Alternate convenience method printf() is given to write a formatted string to this output stream using the specified format string and arguments. These methods internally calling format() method only.

  • public PrintStream printf(String format, Object ... args)
  • public PrintStream printf(Locale l, String format, Object ... args)

Methods to append the specified character to this output stream,

  • public PrintStream append(CharSequence csq)
  • public PrintStream append(CharSequence csq, int start, int end)
  • public PrintStream append(char c)

Another important methods are,

Return typeMethodDescription
voidflush()It flushes the stream
voidclose()It closes the stream. This is done by flushing the stream
and then closing the underlying output stream.
booleancheckError()It flushes the stream and checks its error state.

Java PrintStream class Example

import java.io.PrintStream;
import java.io.FileNotFoundException;
public class PrintStreamDemo {

   public static void main(String[] args)
    throws FileNotFoundException {

      // create PrintStream object
      PrintStream ps = new PrintStream("output.txt");

      // write data 
      ps.println(97);
      ps.println('b');
      ps.println(10.5);
      ps.println(true);
      ps.println("knowprogram");

      // close streams
      ps.close();
   }
}

Output:-

97
b
10.5
true
knowprogram

If the given destination file “output.txt” doesn’t exist then it creates the file itself. (See:- Java program to create files and directories). But if the given file object denotes a directory rather than a file, or if some other error occurs while opening or creating the file then it throws FileNotFoundException.

Whenever we are calling the close() method then first it flushes the stream and then closes the stream. But if automatic flushing is enabled then it will be done every time when one of the println, printf, or format methods is invoked.

Writing data to the console using PrintStream

We can directly use System.out to invoke PrintStream class methods. In System class out, err are two final variables.

  • public static final InputStream in;
  • public static final OutputStream out;
  • public static final OutputStream err;

The in variable holds a BufferedInputStream class object that is connected to the keyboard, whereas out and err variables hold PrintStream class object that is connected to console. Since these variables are static final variables so we can access them directly by using System class names like System.in, System.out, System.err. JVM internally uses System.out to write output to the console and System.err to write exceptions to the console.

public class PrintStreamDemo {
   public static void main(String[] args) {
      // write data to the console
      System.out.println(97);
      System.out.println('b');
      System.out.println(10.5);
      System.out.println(true);
      System.out.println("knowprogram");
   }
}

Difference between write print and println methods

Difference between print and println method

The print method places the cursor in the same line after printing the data so that the next coming output will be printed in the same line. But the println method places the cursor in the next line after printing data so that the next coming output will be printed in the next line.

ps.print('a');
ps.print('b');
ps.print('c');
// Output:-
abc
ps.println('a');
ps.println('b');
ps.println('c');
// Output:-
a
b
c

Difference between print and write method

The print or println method first calls java.lang.String.valueOf() method and the produced string translated into bytes and writes those bytes into the file. Whereas the write method directly converts given number into bytes and write those bytes into the file. Then the file editor showing those bytes as its corresponding ASCII character.

ps.print(97);
ps.print(98);
// Output:-
9798
ps.write(97);
ps.write(98);
// Output:-
ab

Conclusion

To write binary data to the console or file PrintStream is the best choice. But to write character or text data to the console or file, it is not the best choice. The message passed using println() is passed to the server’s console where kernel time is required to execute the task. Kernel time refers to the CPU time. Since println() is a synchronized method, so when multiple threads are passed could lead to a low-performance issue. The println() is a slow operation as it incurs heavy overhead on the machine compared to most IO operations.

PrintWriter class gives high performance compared to PrintStream. PrintWriter class implements most of the methods found in PrintStream class, and constructors are also very similar to PrintWriter. They are fast as compared to the println() of the PrintStream class.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *