Click here to Skip to main content
15,905,874 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I found many programmers using PrintStream in their codes. I looked for this,but failed to get the clear idea of its significance,Why to use it?

"Unlike other output streams, a PrintStream never throws an IOException and the data is flushed to a file automatically i.e. the flush method is automatically invoked after a byte array is written."

So what's the benefit if flush is automatically invoked?

private PrintStream x = null;

Now what could be the possible reasons if someone declares x like this?
Posted
Comments
nameJulian 13-Jun-13 3:20am    
" The PrintStream class enables you to write formatted data to an underlying OutputStream. For instance, writing int, long and other primitive data formatted as text, rather than as their byte values. "
from: http://tutorials.jenkov.com/java-io/printstream.html.

1 solution

A PrintStream simply sits on top of an OutputStream and it's there to provide convenient methods for writing (or indeed printing) to the stream.

Where the OutputStream has a very low-level API (void write(byte[] b, int off, int len)) the PrintStream has methods that allow you to output data types you're likely to have on your objects (void print(String s) or void print(int i)). This makes it easier and to some more natural to use as you don't have to handle converting your data to a byte array before writes.

It also provides things like auto-flush which can be convenient as it's one thing less to worry about.

private PrintStream x = null;
The reason that's declared like that is that the stream is going to be initialized later, most likely when the File or OutputStream is available.

Hope this helps,
Fredrik
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900