CodeGym/Java Blog/Java IO & NIO/Java PrintWriter Class
Author
Volodymyr Portianko
Java Engineer at Playtika

Java PrintWriter Class

Published in the Java IO & NIO group
members

What is the PrintWriter Class in Java?

“PrintWriter is a class used to write any form of data e.g. int, float, double, String or Object in the form of text either on the console or in a file in Java.”
For example, you may use the PrintWriter object to log data in a file or print it on the console.

Why use PrintWriter if other OutputStreams are Available?

The most common practice to print data on the console is by using the System.out.print method. However, it is easier to customize the format as per the specified Locale (regional standards) while publishing global applications using the PrintWriter object. We can look into using Locale according to your system later in this post.

How to Use the PrintWriter Class?

For using the PrintWriter, you need to import the java.io.PrintWriter class. Then after initializing its object, you can use it either for writing on the console or in the file as per your needs. Let’s look at both ways of initialization of the PrintWriter class for the console and the file. There are multiple different constructors present. But here we will introduce to you the simplest ones, to begin with.

Console Output with PrintWriter

Following is a PrintWrtier object to print text on the console.
PrintWriter consoleOutput = new PrintWriter(System.out);
Here the System.out object is passed to the constructor for writing on the console.

File Output with PrintWriter

Here is the PrintWriter object to write text in the file.
PrintWriter fileOutput = new PrintWriter("FileOutput.txt");
This constructor takes a String input as the file name. Creates a file of the specified name and writes the text data in it.

Methods of PrintWriter Class

The Java PrintWriter class comes with a bunch of handy methods. It is harder to swallow just by enlisting them. So, let’s see each one by example. What are they, and how we can use them easily.

Example 1

This example will demonstrate using the PrintWriter object for printing on the console.
import java.io.PrintWriter;

public class PrintWriterDemo {

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


            // by importing the java.io.PrintWriter class
		PrintWriter consoleOutput = new PrintWriter(System.out);

		consoleOutput.printf("Hey there! This is %S.\n", "Lubaina Khan");
		consoleOutput.print("Today you're exploring the PrinWriter class with Code Gym. ");
		consoleOutput.println("Hope you're having fun!");
		consoleOutput.append("Patience is the key when learning new concepts.\n");
		consoleOutput.append("It all boils down to practise and persistence. :)");

		consoleOutput.flush();
		consoleOutput.close();
	}
}

Output

Hey there! This is LUBAINA KHAN. Today you're exploring the PrinWriter class with Code Gym. Hope you're having fun! Patience is the key when learning new concepts. It all boils down to practise and persistence. :)

Used Methods of PrintWriter Class

printf(String str, Object arguments);
The printf() method takes the format for the string to print. Here, the placeholder %S is replaced with the capitalized argument passed next to the string.
print(String str);
This method will print the string passed to it using the PrintWriter object.
println(String str);
A line break is printed after the string contents.
append(CharSequence cs);
The Character Sequence passed to the append is added to the PrintWrtier object.
flush();
Empties the content of the PrintWriter object.
close();
Closes the writing stream and frees any allocated resources.

Example 2

This example will exhibit the use of PrintWriter class for writing data to a file.
import java.io.PrintWriter;
import java.util.Date;
import java.util.Locale;

public class PrintWriterDemo {

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

		try {
                  // by importing the java.io.PrintWriter class
			PrintWriter fileOutput = new PrintWriter("FileOutput.txt");

		      fileOutput.printf(Locale.getDefault(), "Hi, What's the day today? %s.\n", new Date());

			fileOutput.print("Here's an implementation of PrinWriter class for file writing.\n");
			fileOutput.println("Hope Code Gym made it simpler for you to understand.");
			fileOutput.append("One step at a time, and off you go!", 0, 35);

			fileOutput.flush();
			fileOutput.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output

Hi, What's the day today? Sun Jul 25 17:30:21 PKT 2021. Here's an implementation of PrinWriter class for file writing. Hope Code Gym made it simpler for you to understand. One step at a time, and off you go!

Used Methods of PrintWriter Class

Let’s discuss the methods used for file writing that are distinguished from writing on the console.
printf(Locale locale, String str, Object args);
Here you can pass the locale (we have used the System default for coherence) you can use any as per your needs. This complies with any region-based formatting. The rest of the implementation is the same as used before.
append(CharSequence cs, int beginningIndex, int endingIndex);
You can add a chunk of the passed CharSequence by specifying the beginning and ending index of it. Here we have used the last index. You can play around with it to see different outputs.
try{
   ...
} catch (Exception e){
   ...
}
The try-catch block is necessarily used in the file writing. It is to avoid any exceptions while accessing (e.g, permission issues) or creating the file on the system.

Conclusion

That was a quick intro to using the Java PrintWriter Class. Hope it was not overwhelming for you. If it is, we recommend you understand each heading and practice along as you proceed. You’re always welcome back in case of any obstacles. Keep questioning and keep growing.
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet