PrintWriter in Java

In Java, the PrintWriter class is the most enhanced Writer to write character or text data to the file. The biggest advantage of PrintWriter over FileWriter and BufferedWriter is:- we can write any primitive data directly with or without a newline character, and methods of PrintWriter class never throw IOExceptions.

It is defined in the java.io package and it is the subclass of Writer. PrintWriter class can be used to write character data not only to the file but also on the console.

Constructors in PrintWriter class

Since PrintWriter is a connection based, where one end is a Java application and another end is a file or console. We must always pass the file or console information to the constructor. Therefore, it doesn’t contain 0 parameter constructor. PrintWriter can directly communicate to the file and also communicate via some Writer object.

The constructors in PrintWriter class which can directly communicate with file are given below. These constructors are used to write data to the file.

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

The constructors which can communicate with other streams are given below. Generally these constructors are used to write data to the console.

  • public PrintWriter (Writer out)
  • public PrintWriter (Writer out, boolean autoFlush)
  • public PrintWriter(OutputStream out)
  • public PrintWriter(OutputStream out, boolean autoFlush)

The other constructors added in Java10 version are,

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

Methods in PrintWriter class

PrintWriter class contains multiple overloaded methods to write primitive data with or without line separator. This class implements all of the print methods found in PrintStream. In PrintWriter class, if automatic flushing is enabled then it will be done only when one of the println, printf, or format methods is invoked. In the PrintWriter class, none of the methods throw IOException.

Overloaded form of print method,

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

When we call print(char ch) or print(char s[]) then the character is translated into one or more bytes according to the platform’s default character encoding. For print(String s) If the argument is null then the string “null” is printed. Otherwise, the string’s characters are converted into bytes according to the platform’s default character encoding.

For remaining all methods, The string produced by java.lang.String.valueOf(type) is translated into bytes according to the platform’s default character encoding.

In all these method the produced bytes are written in exactly the manner of the write(int) method. Internally every print() is using write(int) method.

The overloaded forms of println methods are,

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

The overloaded forms of println() is used to write data with a line separator. The println() methods directly write a new line. Remaining all methods internally calling print(type) and println() method. For example:-

public void println(int x) {
synchronized (lock) {
print(x);
println();
}}

The overloaded forms of write() method are,

  • write(int c)
  • write(char buf[])
  • write(char buf[], int off, int len)
  • write(String s)
  • write(String s, int off, int len)

Note:- Since all overloaded form of write(), print() and println() method is given to write the data that’s why return type of these methods are void.

The other important methods are,

public void flush()It flushes the stream.
public void close()Closes the stream and releases any system resources associated with it.
public boolean checkError()It flushes the stream if it’s not closed and checks its error state.

Other methods to write the data are,

  • PrintWriter printf(String format, Object ... args)
  • PrintWriter printf(Locale l, String format, Object ... args)
  • PrintWriter format(String format, Object ... args)
  • PrintWriter format(Locale l, String format, Object ... args)
  • PrintWriter append(char c)
  • PrintWriter append(CharSequence csq)
  • PrintWriter append(CharSequence csq, int start, int end)

Printwriter Java Example

Java program to demonstrate methods of PrintWriter class and saving data to the file.

import java.io.PrintWriter;
import java.io.FileNotFoundException;
public class PrintWriterDemo {

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

      // create object or PrintWriter
      PrintWriter pw = new PrintWriter("output.txt");

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

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

The data in output.txt is,
97
b
10.5
true
knowprogram

Whenever close() method is called on PrintWriter object then first it flushes the data from stream to file and then close the connection. But if automatic flushing is enabled then it will be done everytime when one of the println, printf, or format methods is invoked.

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.

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

pw.println('a');
pw.println('b');
pw.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.

pw.print(97);
pw.print(98);
// Output:-
9798

pw.write(97);
pw.write(98);
// Output:-
ab

Writing data to the console using PrintWriter

To create PrintWriter class object connecting to the console,

  • Pass System.out as an argument to OutputStreamWriter object creation
  • pass OutputStreamWriter as an argument to PrintWriter object creation

OutputStreamWriter osw = new OutputStreamWriter(System.out);
PrintWriter pw = new PrintWriter(osw);

Java program to use PrintWriter class to write data to the console

import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class PrintWriterDemo {
   public static void main(String[] args) {

      // create PrintWriter object
      PrintWriter pw = new PrintWriter(
             new OutputStreamWriter(System.out));

      // write data to the file
      pw.println(97);
      char[] ch1 = {'a', 'b', 'c', 'd'};
      pw.println(ch1);
      pw.println("knowprogram");
      pw.println("Hello, World!");

      // close stream
      pw.close();
   }
}

Output:-
97
abcd
knowprogram
Hello, World!

Advantage of Java PrintWriter class

1) We can write any primitive data directly.
2) Data can be written with or without a new line character.
3) Methods of PrintWriter class never throw IOExceptions.
4) PrintWriter class can write data both on the file or the console.

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 *