JavaPrintWriter

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java PrintWriter class

Java PrintWriter class is the implementation of Writer class. It is used to print the formatted representation of objects to the text-output stream.

Class declaration

Let's see the declaration for Java.io.PrintWriter class:

  1. public class PrintWriter extends Writer  

Methods of PrintWriter class

Method

Description

void println(boolean x)

It is used to print the boolean value.

void println(char[] x)

It is used to print an array of characters.

void println(int x)

It is used to print an integer.

PrintWriter append(char c)

It is used to append the specified character to the writer.

PrintWriter append(CharSequence ch)

It is used to append the specified character sequence to the writer.

PrintWriter append(CharSequence ch, int start, int end)

It is used to append a subsequence of specified character to the writer.

boolean checkError()

It is used to flushes the stream and check its error state.

protected void setError()

It is used to indicate that an error occurs.

protected void clearError()

It is used to clear the error state of a stream.

PrintWriter format(String format, Object... args)

It is used to write a formatted string to the writer using specified arguments and format string.

void print(Object obj)

It is used to print an object.

void flush()

It is used to flushes the stream.

void close()

It is used to close the stream.

Java PrintWriter Example

Let's see the simple example of writing the data on a console and in a text file testout.txt using Java PrintWriter class.

  1. package com.tutorialtours;  
  2.   
  3. import java.io.File;  
  4. import java.io.PrintWriter;  
  5. public class PrintWriterExample {  
  6.     public static void main(String[] args) throws Exception {  
  7.              //Data to write on Console using PrintWriter  
  8.       PrintWriter writer = new PrintWriter(System.out);    
  9.       writer.write("Javatpoint provides tutorials of all technology.");        
  10.  writer.flush();  
  11.       writer.close();  
  12. //Data to write in File using PrintWriter       
  13.       PrintWriter writer1 =null;      
  14.          writer1 = new PrintWriter(new File("D:\testout.txt"));  
  15.          writer1.write("Like Java, Spring, Hibernate, Android, PHP etc.");                                                   
  16.                          writer1.flush();  
  17.          writer1.close();  
  18.     }  
  19. }  

Outpt

tutorialtours provides tutorials of all technology.

The content of a text file testout.txt is set with the data Like Java, Spring, Hibernate, Android, PHP etc.