Katerina Zamani

About 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.

PrintWriterClass.java:

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
		pw.flush();
		
		System.out.println("\n---------------------------------------");
		
		// write sth in a file (deletes the lines if exist)
		PrintWriter pwFile = null;
		Date date = new Date();
		try{
			pwFile = new PrintWriter(filename);
			i++;
			// write a builtIn object
			pwFile.println(date);
			pwFile.write("Write something in a line. i = "+i);
			System.out.println("Write to the file successfully");
		}catch(FileNotFoundException e) {
            e.printStackTrace();
        }catch(SecurityException e) {
        	e.printStackTrace();
        }finally {
            // always close the output stream
        	if(pwFile != null){
                pwFile.close();
            }
        }
		
		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) ;       
			
			pwFile1.println(obj);
			// 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) {
		    e.printStackTrace();
		}catch(SecurityException e) {
		    e.printStackTrace();
		} catch (IOException e) {
			// for FileWriter
			e.printStackTrace();
		}finally {
		   // no matter what happen, close the output stream
			if(pwFile1 != null){
				pwFile1.close();
		   }
		}
	}

}

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.

Output:

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.

jcgFile.txt:

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

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 two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close