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.

Java PrintWriter 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.

Java PrintWriter 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.

The PrintWriter class in Java is a powerful tool for writing formatted text to output streams, including files. This article supplements existing knowledge with detailed examples of working with File objects, creating new files programmatically, and highlighting the importance of properly closing PrintWriter to ensure efficient file handling operations.

1. Using File Objects with PrintWriter

To write to a file using PrintWriter, you first need to create a File object representing the target file. Here’s a detailed example:

Example: Writing to a File

import java.io.File;
import java.io.PrintWriter;

public class PrintWriterFileExample {
    public static void main(String[] args) {
        try {
            // Create a File object
            File file = new File("example.txt");

            // Initialize PrintWriter with the File object
            PrintWriter writer = new PrintWriter(file);

            // Write data to the file
            writer.println("Hello, World!");
            writer.println("This is a test file.");
            writer.println("PrintWriter makes file handling easy.");

            // Close the PrintWriter
            writer.close();

            System.out.println("File written successfully.");
        } catch (Exception e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}

Output: Creates a file named example.txt with the specified content.

2. Creating a New File Using File and PrintWriter

Before writing to a file, it’s important to ensure the file exists. If it doesn’t, you can create it programmatically using the createNewFile() method of the File class.

Example: Creating and Writing to a New File

import java.io.File;
import java.io.PrintWriter;

public class CreateNewFileExample {
    public static void main(String[] args) {
        try {
            // Create a File object
            File file = new File("newfile.txt");

            // Check if the file exists, and create it if it doesn’t
            if (file.createNewFile()) {
                System.out.println("File created: " + file.getName());
            } else {
                System.out.println("File already exists.");
            }

            // Initialize PrintWriter with the File object
            PrintWriter writer = new PrintWriter(file);

            // Write data to the file
            writer.println("This is a newly created file.");
            writer.println("Java makes file handling straightforward.");

            // Close the PrintWriter
            writer.close();

            System.out.println("Data written to the file successfully.");
        } catch (Exception e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}

Output: Creates a new file named newfile.txt if it does not already exist and writes the specified data to it.

3. Importance of Closing PrintWriter

It is crucial to close the PrintWriter after completing file operations to:

  • Free System Resources: Ensures that file descriptors and other resources are released.
  • Flush Data: Guarantees that any buffered data is written to the file.
  • Prevent Data Corruption: Minimizes the risk of incomplete writes or corrupted files.

Example: Closing PrintWriter in a finally Block

import java.io.File;
import java.io.PrintWriter;

public class EnsureCloseExample {
    public static void main(String[] args) {
        PrintWriter writer = null;

        try {
            // Create and initialize PrintWriter
            File file = new File("safeclose.txt");
            writer = new PrintWriter(file);

            // Write data to the file
            writer.println("Always close resources properly.");
        } catch (Exception e) {
            System.out.println("An error occurred: " + e.getMessage());
        } finally {
            // Ensure the PrintWriter is closed
            if (writer != null) {
                writer.close();
            }
        }
    }
}

This approach ensures that PrintWriter is closed even if an exception occurs during file operations.

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.