Home » Core Java » io » PrintWriter » Java PrintWriter Example

About Katerina Zamani

Katerina Zamani
Katerina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she attends MSc courses in Advanced Information Systems at the same department. Currently, her main academic interests focus on web applications, mobile development, software engineering, databases and telecommunications.

Java PrintWriter Example

Java provides us PrintWriter class, from which we can print formatted and human readable data in a stream. The text-output stream can be either OutputStream or Writer. More specifically it doesn’t contain methods for printing the primitive types (for instance int, long etc) as byte values, but as text-format representation.

In this example, we are going to print some common data types to the standard output as well as to a file.


1. Example of PrintWriter

Create a java class with name PrintWriterClass and paste the following code.


package com.javacodegeeks.core.printwriter;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class PrintWriterClass {

	final static String filename = "C:/JCG/jcgFile.txt";
	public static void main(String[] args) {
		// the standard output as OutputStreamWriter
		PrintWriter pw = new PrintWriter(System.out, true);
		pw.println("Java Code Geeks");
		int i = 5;
		double k = 10.0;
		pw.printf("i = %d and k = %f",i,k);
		// flush the instance pw
		// write sth in a file (deletes the lines if exist)
		PrintWriter pwFile = null;
		Date date = new Date();
			pwFile = new PrintWriter(filename);
			// write a builtIn object
			pwFile.write("Write something in a line. i = "+i);
			System.out.println("Write to the file successfully");
		}catch(FileNotFoundException e) {
        }catch(SecurityException e) {
        }finally {
            // always close the output stream
        	if(pwFile != null){
		PrintWriter pwFile1 = null;
		Object obj = System.getProperty("line.separator")+"A new object";
		// write in a file in a newline (no deletion of previous writing)
		try {
			FileWriter fl = new FileWriter(filename, true);
			BufferedWriter br = new BufferedWriter(fl);
			pwFile1 = new PrintWriter(br) ;       
			// write the string beginning from the 3rd char until the 8th
			pwFile1.write("!!!JCG Test!!!",3 ,8);
			System.out.println("Add new lines to the file successfully");
		}catch(FileNotFoundException e) {
		}catch(SecurityException e) {
		} catch (IOException e) {
			// for FileWriter
		}finally {
		   // no matter what happen, close the output stream
			if(pwFile1 != null){


As you can see from the code above, we have different instances of PrintWriter class, in order to show different situations.

Firstly, we create the pw instance from the existing System.out OutputStreamWriter. Also we set the second parameter to true, so the printing methods will flush the output buffer. As you can notice, println() and printf() methods are called and the standard output will convert characters into bytes with the use of the default character encoding. For int and double data types, %d
and %f should be declared in the printf() method. flush() method is used in order to flush the stream.

The second instance – pwFile – represents a PrintWriter with a specified file, in order to write into a specific file. We should declare the full path of the file, which denotes the destination of this writer. It is worth to mention that if the file doesn’t exist, it will be created. Also notice that we should throw FileNotFoundException if the file doesn’t represent an existing writable regular file, as well as SecurityException for write access permissions. In this situation println() method is called again, where it prints the built-in object (Date) and terminates the line. In addition, write() method writes the specified string to the file.

Finally, we create pwFile1 instance and we set BufferedWriter as character-output stream. For the instance of BufferedWriter we should use FileWriter class too by setting the specified file as parameter. In this situation, we can print/write into the file but without deleting the previous lines. As you can notice, println() prints an object that we created. Also, we use write() method with specific parameters in order to write a part of the specified string. Essentially, we declare a string in the first parameter then we set the offset from which the writing is beginning and finally we set the number of writing characters to the last parameter.

It is worth to mention that we should close the stream, so close() method is called into finally block. So, even if an exception is thrown, the stream always closes and any associated system resources are released.

Below you can see the output of the execution.


Java Code Geeks
i = 5 and k = 10.000000
Write to the file successfully
Add new lines to the file successfully

Also, you can see what the stream wrote into the file during the execution.


Wed Mar 19 13:25:08 EET 2014
Write something in a line. i = 6
A new object
JCG Test

Download the source file

This was a tutorial about PrintWriter in Java. Download the source code of this example: PrintWriterExample.zip

(No Ratings Yet) Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area


Leave a Reply

Be the First to Comment!

Notify of