Java PrintStream Class
PrintStream from the java.io package offers useful methods for writing data to the console and files as well as output streams. This class manages data flushing automatically while preventing IOExceptions from occurring but provides error status checks through .checkError().
Syntax:
import java.io.PrintStream;
Creating a PrintStream Object
From System.out (Console Output)
PrintStream ps = System.out;
ps.println("Hello from PrintStream!");
From a File Output Stream
import java.io.*;
PrintStream ps = new PrintStream(new FileOutputStream("output.txt"));
ps.println("This will be written to a file.");
ps.close(); // Always close to flush and free resources
Methods of PrintStream
| Method | Description |
|---|---|
| print() | Prints without a newline |
| println() | Prints with a newline |
| printf() | Prints formatted text (like C's printf) |
| write() | Writes raw bytes |
| append() | Appends characters or sequences |
| checkError() | Returns true if any error has occurred |
| close() | Closes the stream |
Example:
import java.io.PrintStream;
public class PrintStreamDemo {
public static void main(String[] args) {
PrintStream ps = System.out;
ps.print("Hello, ");
ps.println("World!");
ps.printf("Number: %d, Decimal: %.2f", 10, 3.14159);
}
}
Output
Hello, World! Number: 10, Decimal: 3.14
Example:
Writing to a File
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class FilePrintStreamExample {
public static void main(String[] args) {
try {
PrintStream ps = new PrintStream("log.txt");
ps.println("Logging started...");
ps.printf("Log ID: %d, Status: %s%n", 101, "SUCCESS");
ps.close();
} catch (FileNotFoundException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
- PrintStream is not synchronized. You can use PrintWriter when you need to perform advanced character writing operations with enhanced control features.
- System.out serves as a PrintStream object which allows System.out.println() and System.out.print() methods to function within this class.
- Ensuring data reaches its destination requires calling either flush() or close().
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com