In Java, there are various methods to print the data on the console. The “System.out.print()” is the most conventional approach. However, the Java “PrintWriter” class can also be used for this purpose. This class enables the programmer to write and append the data on the console as well as the file. As a result, this approach is helpful in updating the data from time to time.
What is the “PrintWriter” Class in Java?
This class is the implementation of the “Writer” class and extends it. It is used to write the data of both the primitive as well as non-primitive types to the file or console in Java.
Working of the “PrintWriter” Class
This class returns the conversion in a text format and then writes this formatted data to the writer. It also contains the auto flush functionality that implies that the writer is forced to write the entire data upon the invoked “print” methods.
Note: This method does not return any exception. However, a faced error can be analyzed manually via the class “checkError()” method.
How to Use the Java “PrintWriter” Class?
The “PrintWriter” class can be used once its relevant package “java.io.PrintWriter” is imported. After that, this class can be used to print/write the data on the file or console depending upon the user’s requirements.
Declaration Syntax
public class PrintWriter extends Writer
Syntax(Printing Data on Console)
PrintWriter object= new PrintWriter(System.out);
Here, “System.out” signifies that the written content will be printed to the console.
Syntax (Printing Data to File)
PrintWriter object = new PrintWriter("file.txt");
In this syntax, “file.txt” represents the text file in which the data is to be written.
PrintWriter Class Methods
Methods | Functionality |
---|---|
println(dt a) | This method prints the values of multiple types such as integer, float, character, string, etc, and places the cursor on the next line. |
append(char a) | It appends the target character or a sequence to the writer. |
append(CharSequence char, int x, int y) | It appends a subsequence of the characters in the given start i.e., “x” and end i.e., “y” intervals. |
setError() | This method implies if an error is faced. |
checkError() | It checks the error state of the stream. |
format(String x, Object…args) | It writes a string(formatted) to the writer. |
print(x) | It also prints the primitive i.e., int, char, and non-primitive i.e., String, object values. |
flush() | It flushes the stream. |
close() | It closes the stream. |
Example 1: Using the Java “PrintWriter” Class to Write Data on Console
In this example, the “PrintWriter” class writes the data on the console:
package jbArticles;
import java.io.PrintWriter;
public class Printwriter {
public static void main(String[] args){
PrintWriter object = new PrintWriter(System.out);
object.write("He is a smart programmer!" + "\n");
object.write("Liam", 1, 2);
object.write("\n" +1);
object.flush();
object.close();
}}
Code Explanation
- Incorporate the specified package to use the “PrintWriter” class.
- Create a PrintWriter class object having “System.out” as the constructor’s parameter.
- Apply the “write()” method to write the given string on the console.
- Use the method again to print the string at specified intervals.
- Lastly, write the integer on the console and flush the steam via the “flush()” method.
Output
Example 2: Using the Java “PrintWriter” Class to Write Data to File
This specific example uses the class to write and append the string data to the file instead:
package jbArticles;
import java.io.PrintWriter;
public class Printwriter {
public static void main(String[] args) throws Exception{
PrintWriter object = new PrintWriter("file.txt");
object.write("This is JavaBeat site!");
object.append("\nIt is an informative site");
object.flush();
object.close();
}}
Code Explanation
- In the created “PrintWriter” object, specify the file in which the data is to be written.
- Write the specified string statement to the file.
- Use the “append()” method to append the given string to update the file content.
- Note: Upon running the code, the named file will be created automatically and the specified content will be written to it.
- Flush and close the stream, respectively.
Output
Example 3: Applying the Java “PrintWriter” Class Methods
In this scenario, the discussed class methods print the values of both the types i.e., (primitive and non-primitive) using different methods:
package jbArticles;
import java.io.PrintWriter;
public class Printwriter {
public static void main(String[] args) throws Exception{
String a = "Liam";
char b = 'x';
char c[] = {'a', 'b', 'c'};
double d = 23323.4567632312321;
float f = 23.45f;
int h = 3;
long i = 92987256;
Object j = "David";
PrintWriter object = new PrintWriter(System.out);
object.printf("String Value -> " + "This is %s", a + "\n");
object.println("Boolean Value -> " + true);
object.append("Appended Character Value -> " +b + "\n");
object.println(c);
object.print("Double Value -> " +d);
object.println("\nFloat Value -> " +f);
object.println("Integer Value -> " +h);
object.println("Long Value -> " +i);
object.println("Object Value -> " +j);
object.flush();
object.close();
}}
Code Explanation
- Initialize the values of both types.
- Create a “PrintWriter” instance signifying that the data is to be logged on the console.
- Use the “printf()” method to print the formatted string via “%s”.
- Apply the “println()” method to display the boolean value and place the cursor on the next line.
- Utilize the “append()” method to append the character value.
- Display the character array in the next line.
- Implement the “print()” method to print the double value.
- Note: In the next printing, “\n” is followed by the float value since there was no line break due to the applied “print()” method in the last step.
- Likewise, use the “println()” methods to display the integer, long, and object values.
Output
Example 4: Using the Java “PrintWriter” Class to Set and Check the Error
In the below demonstration, the class methods “setError()” and “checkError()” indicate and check for an error, if faced, respectively. This example fetches the ASCII representation of the character array values:
package jbArticles;
import java.io.OutputStream;
import java.io.PrintWriter;
public class Printwriter extends PrintWriter {
public Printwriter(OutputStream ret) {
super(ret);
}
public static void main(String[] args) {
char array[] = {65, 66, 67};
String y = "Liam";
Printwriter object = new Printwriter(System.out);
object.write(array);
object.write("\n" + y);
object.flush();
object.setError();
boolean z = object.checkError();
System.out.println("\nIs there any error? " + z);
}}
Code Explanation
- Define the public class “Printwriter” that extends the “PrintWriter” class.
- Create a class constructor that makes a new PrintWriter from the present OutputStream.
- In “main”, declare a character array containing the ASCII characters and initialize a string value.
- Instantiate the Printwriter public class such that the written content is logged on the console.
- Use the “write()” method to display the characters in an array as ASCII characters and the string value.
- Apply the “setError()” method to indicate an error.
- Also, utilize the “checkError()” method to analyze if there is any error in the stream which is logged as a boolean.
Output
Why Prefer “PrintWriter” Over the Other OutputStreams?
Although the “print” stream can be used to print the output, the “PrintWriter” class is preferred when there is a need to write the data on both the console and file. Also, this class/stream is favorable in the case of analyzing the faced errors in the stream with minimal code. This resultantly assists in enhancing the space complexity of the code.
What is the Difference Between “FileWriter” and “PrintWriter” in Java?
The “FileWriter” class is used for writing characters into a file. The “PrintWriter” class, however, has multiple features. It means that it can be utilized for writing to other output streams i.e., console as well as a file.
Conclusion
The “PrintWriter” class is used to write the data of various types to multiple output streams such as file, and console. This class includes several methods for printing and appending data of both the primitive and non-primitive types. Also, it has methods for identifying the errors, if any in the code.