Printwriter

The PrintWriter class in Java is an implementation of the Writer class and is utilized for printing the formatted version of objects to the text output stream.

The PrintWriter class offers convenient functions for writing different data types like integers, doubles, and strings to a file or another output source. It is commonly utilized alongside other input/output classes such as FileWriter or BufferedWriter to effectively write data to files. An important benefit of employing PrintWriter is its automatic management of line breaks and conversion of primitive data types into text formats. Furthermore, it provides functionalities for formatting output through printf-style formatting. In summary, PrintWriter streamlines the procedure of composing formatted textual data to output streams within Java programs.

Class Declaration

Now, let's examine the declaration of the Java.io.PrintWriter class:

Example

public class PrintWriter extends Writer

When you set up a PrintWriter for file output, you have the option to define the character encoding. This becomes crucial when handling non-ASCII characters or when ensuring interoperability with particular platforms. For instance, you can define the encoding like this:

Example

PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream("file.txt"), StandardCharsets.UTF_8));

Exception Handling

It is crucial to address any potential exceptions that might arise when performing file I/O operations with PrintWriter. Errors such as FileNotFoundException and IOException are examples of exceptions that could be raised when interacting with files. Implementing effective exception handling guarantees that your program responds appropriately when encountering issues.

Methods of PrintWriter class

Method Description
void println(boolean x) It is used to print the boolean value.
void println(char[] x) It is used to print anarrayof characters.
void println(int x) It is used to print an integer.
PrintWriter append(char c) It is used to append the specified character to the writer.
PrintWriter append(CharSequence ch) It is used to append the specified character sequence to the writer.
PrintWriter append(CharSequence ch, int start, int end) It is used to append a subsequence of specified character to the writer.
boolean checkError() It is used to flushes the stream and check its error state.
protected void setError() It is used to indicate that an error occurs.
protected void clearError() It is used to clear the error state of a stream.
PrintWriter format(String format, Object... args) It is used to write a formattedstringto the writer using specified arguments and format string.
void print(Object obj) It is used to print an object.
void flush() It is used to flushes the stream.
void close() It is used to close the stream.
void println(double x) Prints a double value.
void println(float x) Prints a float value.
void println(long x) Prints a long value.
void println(String x) Prints a string.
void write(char[] buf) Writes an array of characters.
void write(char[] buf, int off, int len) Writes a portion of an array of characters.
void write(int c) Writes a single character.
void write(String s) Writes a string.
void write(String s, int off, int len) Writes a portion of a string.
PrintWriter format(Locale l, String format, Object... args) Writes a formatted string to the writer using the specified locale, format string, and arguments.
PrintWriter printf(String format, Object... args) Writes a formatted string to the writer using the specified format string and arguments.

Java PrintWriter Example

Let's examine a straightforward illustration of how to output data to both the console and a text file named testout.txt by utilizing the Java PrintWriter class.

Filename: PrintWriterExample.java

Example

package com.example;



import java.io.File;

import java.io.PrintWriter;

public class PrintWriterExample {

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

             //Data to write on Console using PrintWriter

	  PrintWriter writer = new PrintWriter(System.out);	 

	  writer.write("C# Tutorial provides tutorials of all technology.");  	 

 writer.flush();

	  writer.close();

//Data to write in File using PrintWriter	  

	  PrintWriter writer1 =null;	

  		 writer1 = new PrintWriter(new File("D:\\testout.txt"));

  		 writer1.write("Like Java, Spring, Hibernate, Android, PHP etc.");  		                                       

                         writer1.flush();

	     writer1.close();

 	}

}

Output

Output

C# Tutorial provides tutorials of all technology.

Testout.txt

Example

Like Java, Spring, Hibernate, Android, PHP etc.

Explanation

In Java, the code utilizes the PrintWriter class to facilitate writing data to both a file and the console. To output text to the console, the initial step involves creating an instance of PrintWriter named writer, which is linked to the standard output stream.

In order to ensure rapid output, the println function displays the specified string on the console and then clears it. Any resources used by the PrintWriter are freed up by invoking the close method. Subsequently, a fresh File instance named "testout.txt" is linked to a different PrintWriter named writer1, enabling data to be recorded in that file within the present directory. The methods println, flush, and close are employed for writing the string to the file promptly, ensuring immediate data recording, and properly managing resources similar to console output.

Conclusion

In summary, the PrintWriter class in Java offers a convenient approach for writing formatted text content to output streams, which can be files or the console. Its synergy with other I/O classes like FileWriter and BufferedWriter enhances data processing efficiency.

The class provides versatility to meet various application needs by presenting a variety of techniques to format output and print various types of data. Additionally, PrintWriter includes built-in mechanisms for handling exceptions, which streamline error management and ensure smooth handling of any potential errors that may arise during file input/output operations. In summary, this class streamlines the task of writing text data in Java applications by offering robust error-handling features, adaptability, and user-friendly functionality.

Input Required

This code uses input(). Please provide values below: