PrintWriter in Java | Example Program

PrintWriter in Java is a character output stream that creates a file and writes output data to a text file in a human-readable format.

It provides several methods to print strings and numbers in text format.

The methods of PrintWriter never throw IOException when errors occur but they set an internal flag we can check by calling checkError() method.


Note:

1. For reading strings and numeric values from a text file, use Scanner class.
2. For writing strings and numeric values to a text file, use PrintWriter class.

Java PrintWriter class declaration


PrintWriter class is a subclass of Writer class that extends Object class. It implements Closeable, Flushable, Appendable, and AutoCloseable interfaces.

The general syntax to declare PrintWriter class in Java is as follows:

public class PrintWriter
     extends Writer
           implements Closeable, Flushable, Appendable, AutoCloseable

The inheritance hierarchy diagram for PrintWriter class is as follows:

java.lang.Object
    java.io.Writer
        java.io.PrintWriter

Constructors of PrintWriter class


PrintWriter class defines the following constructors in Java that are as follows:

1. PrintWriter​(File file): This constructor creates a PrintWriter object with the specified file, without automatic line flushing.

The general syntax to create an object of PrintWriter with the specified file is as follows:

FileWriter fw = new FileWriter("myfile.txt");
PrintWriter pw = new PrintWriter(fw);

2. PrintWriter​(File file, String charSet): This constructor creates a PrintWriter object with the specified file and charset, without automatic line flushing.


3. PrintWriter​(File file, Charset charset): This form of constructor creates a PrintWriter object with the specified file and charset, without automatic line flushing.

4. PrintWriter​(OutputStream os): This constructor creates a PrintWriter object with specified OutputStream os without automatic line flushing.

5. PrintWriter​(OutputStream os, boolean autoFlush): This constructor creates a PrintWriter object with specified OutputStream os. If autoFlush is true, it flushes the Writer after every call to println.


6. PrintWriter​(OutputStream os, boolean autoFlush, Charset charset): This overloaded constructor creates a PrintWriter object with specified OutputStream os and charset.

7. PrintWriter​(Writer wr): This form of constructor creates a PrintWriter object with specified Writer wr, without automatic line flushing.

8. PrintWriter​(Writer wr, boolean autoFlush): This constructor creates a PrintWriter object with the specified Writer wr. If the autoFlush is true, it flushes the Writer after every call to println.

9. PrintWriter​(String filename): This constructor creates a PrintWriter object with the specified file name, without automatic line flushing.

The general syntax to create an object of PrintWriter with the specified filename is as follows:

PrintWriter pw = new PrintWriter(filename);

10. PrintWriter​(String fileName, String charSet): This constructor constructs a PrintWriter object with the specified file name and charset, without automatic line flushing.

11. PrintWriter​(String fileName, Charset charset): This form of constructor creates a PrintWriter object with the specified file name and charset, without automatic line flushing.


If autoFlush parameter defined in the above constructors is true, the output buffer is automatically flushed every time a println(), printf(), or format() is called.

Methods of PrintWriter Class in Java


In addition to methods inherited from Writer class, PrintWriter class also define some useful methods that are as follows:

1. PrintWriter append​(char c): This method appends the specified character to this print writer.

2. PrintWriter append​(CharSequence csq): This method appends the specified character sequence to this print writer.

3. PrintWriter append​(CharSequence csq, int start, int end): This method appends a subsequence of the given character sequence to this writer.

4. boolean checkError(): The checkError() method flushes the stream if it is not closed and checks its error state. If any exception has occurred while writing values to that stream, the checkError() method returns true.

5. protected void clearError(): The clearError() method is used to clear the error state of this stream.


6. void close(): This method closes the stream and releases any system resources associated with it.

Note: You must close the print stream when you are completed writing output. If you exit from the program without closing PrintWriter, the file may not have all of the output.

7. void flush(): This method flushes the stream.

8. void print​(boolean b): It is used to write a boolean value to a file. In other words, it prints a boolean value.

9. void print​(char c): It is used to write a character to the file. It prints a character.

10. void print​(char[ ] cArray): It is used to write an array of characters to the file. It prints an array of characters.


11. void print​(double d): It is used to write a double value to the file. That is, it prints a double-precision floating-point number.

12. void print​(float f): It is used to write a float value to the file. That is, it prints a floating-point number.

13. void print​(int i): It is used to write an int value to the file. That is, it prints an integer value.

14. void print​(long l): It is used to write a long value to the file. That is, it prints a long value.

15. void print​(Object obj): It is used to write an object to the file. That is, it prints an object.


16. void print​(String s): It is used to write a string value to the file. That is, it prints a string value.

17. void println(): This method is used to terminate the current line by writing the line separator string.

18. void println​(boolean x): This method is used to print a boolean value and then terminates the line.

19. void println​(char x): This method is used to print a character and then terminates the line.

20. void println​(char[ ] x): This method is used to print an array of characters and then terminates the line.


21. void println​(double x): This method is used to print a double-precision floating-point number and then terminates the line.

22. void println​(float x): This method is used to print a floating-point number and then terminates the line.

23. void println​(int x): It is used to print an integer value and then terminates the line.

24. void println​(long x): It is used to print a long integer value and then terminates the line.

25. void println​(Object x): It is used to print an Object and then terminates the line.


26. void println​(String x): It is used to print a string and then terminates the line.

27. protected void setError(): The setError() method is used to indicate that an error has occurred.

28. void write​(char[ ] buf): This method is used to write an array of characters.

29. void write​(char[ ] buf, int offset, int length): This method is used to write a portion of an array of characters.

30. void write​(int c): It is used to write a single character.


31. void write​(String s): It is used to write a string.

32. void write​(String s, int offset, int length): This method is used to write a portion of a string.

33. PrintWriter printf​(String format, Object… args): This method is used to write a formatted string to the writer using the specified format string and arguments.

34. PrintWriter format​(String format, Object… args): This method is used to write a formatted string to the writer using the specified format string and arguments.

Example Programs based on PrintWriter


1. Let’s take a simple example program where we will write data to the console and a text file. Look at the source code.

Program source code 1:

package javaPackage;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class PrintWriterExample {
public static void main(String[] args) throws IOException 
{
// Data to write on Console using PrintWriter class.
// Create an object of PrintWriter class using System.out.
     PrintWriter pw = new PrintWriter(System.out);    
    
     pw.write("Scientech Easy provides tutorials of all technology.");        
     pw.flush();  
     pw.close();  
 
// Data to write in File using PrintWriter class.       
     PrintWriter pw2 = new PrintWriter(new FileWriter("D:\\myfile.txt"));  
      pw2.write("Like Java, Python, HTML, Android, PHP, Javascript etc.");                                                   
      pw2.flush();  
      pw2.close();  
 }
}
Output:
           Scientech Easy provides tutorials of all technology.

Contents written to myfile.txt file:

Like Java, Python, HTML, Android, PHP, Javascript etc.

Hope that this tutorial has elaborated all the important points related to PrintWriter class in Java with example program. I hope that you will have understood the basic concepts of PrintWriter class.
Thanks for reading!!!
Next ⇒ Scanner Class in Java

⇐ Prev Next ⇒