Java 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: ThePrintWriterto 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-catchmethod while performing file operations using thePrintWriteror 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
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours