Java PrintStream Class
The PrintStream
class in Java is a specialized output stream used to print data in a human-readable format. It extends the FilterOutputStream
class and adds functionality to write formatted representations of objects to the output stream.
1. Why Use PrintStream?#
While FileOutputStream
and BufferedOutputStream
work well for raw byte operations, PrintStream
is ideal for:
- Printing textual representations of data
- Automatically flushing output
- Writing formatted output without needing manual conversions
You might already be familiar with it — System.out
is a PrintStream
object!
2. Creating a PrintStream Object#
You can create a PrintStream
using various constructors:
3. Key Methods in PrintStream (With Examples)#
● void print(String s)
#
Prints a string to the stream.
Output (content inside output.txt):#
● void println(String s)
#
Prints a string followed by a newline character.
Output:#
● void printf(String format, Object... args)
#
Prints a formatted string using the specified format and arguments.
Output:#
● void write(int b)
#
Writes the specified byte to the stream. Useful for writing binary data.
Output:#
● void flush()
#
Forces any buffered output bytes to be written out. Usually not needed when using println
, but good to know.
● void close()
#
Closes the stream and releases any system resources associated with it.
4. Special Note: System.out is a PrintStream#
You use it every day without realizing:
It behaves just like the examples shown above.
5. When Should You Use PrintStream?#
- When you want to print nicely formatted, human-readable output
- When writing data to files and you want to use print/println/printf features
- When you don’t need to worry about character encoding or internationalization (for that, use
PrintWriter
)
Conclusion#
In this blog, we learned about the PrintStream
class, which is commonly used for writing formatted and human-readable output in Java. We explored its key methods like print
, println
, printf
, write
, flush
, and close
with practical examples. This class is extremely useful for logging and writing text data to files.