PrintWriter
Anonymous contributor
Published Aug 17, 2024
Contribute to Docs
PrintWriter
is a class in Java that is used for writing text in readable form. It is a part of the java.io
package and provides convenient methods for writing different types of data (like strings, numbers, or objects) to a file or another output stream in a human-readable, formatted way.
Syntax
PrintWriter writer = new PrintWriter(new File(file_name));
writer.println(text);
writer.close();
writer
: ThePrintWriter
to be used for writing text.file_name
: The file to which the text is to be written. If it does not exist, then a new file is created.text
: The text to be written to the file.
Example
The below example shows how to use the PrintWriter
class:
import java.io.File;import java.io.PrintWriter;import java.io.FileNotFoundException;public class Example {public static void main(String[] args) {try {PrintWriter writer = new PrintWriter(new File("output.txt"));writer.println("Hello, world!");writer.close();} catch (FileNotFoundException e) {e.printStackTrace();}}}
Note: The usage of the
try-catch
method while performing file operations using thePrintWriter
or any other class is essential to handle potential errors gracefully, ensure resources are properly managed, and provide a better user experience.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours