Take the 2-minute tour ×

i mean if i have to create a method some kind of a: void setOutputStream(PrintStream stream). so the stream variable is an output stream where i'll write my data(which will preferrebly be a String variable). the question is, how it will dynamically determine the outtup stream and correctly write my data there, i.e. for System.out it'll print data on the screen, for file stream it'll write my data to the file. thanks

share|improve this question

4 Answers 4

up vote 2 down vote accepted

I think you're looking for java.lang.System#setOut(PrintStream stream) method. Which essentially lets you reassign the standard output stream programmatically.

share|improve this answer
i think,that's what i needed. thanks! –  Helgus Feb 27 '12 at 14:28

I think that something is wrong in your question, the point is that the PrintStream itself use a OutputStream that is passed to it when you create it, as you can see here. So you have to pass the correct PrintStream at the method which write in your OutputStream. I think that you just need to do a method like:

PrintStream createPrintStream(OutputStream out, String(or what you want) type);

and then pass the returned print stream to the method which will write on it.

Maybe the factory design pattern can help you Factory Method Design Pattern

share|improve this answer

What you want to do is called Decorator pattern. You might want to review this answer (and the thread).

Look at the following class hierarchy (java.io.*Stream)

    java.io.Console (implements java.io.Flushable) 
    java.io.File (implements java.lang.Comparable<T>, java.io.Serializable) 
    java.io.InputStream (implements java.io.Closeable) 
                    java.io.DataInputStream (implements java.io.DataInput) 

Good Luck!

share|improve this answer
it describes only File io, but i need another way of implementation –  Helgus Feb 27 '12 at 14:25
The idea is the same for all java.io.*streams the entire hierarchy implements the Decorator pattern and this is what you need to do. –  aviad Feb 27 '12 at 14:28

You can create a basic OutputStream that writes to a file using:

OutputStream out = new FileOutputStream(filename)

You can then create a PrintStream from that using:

PrintStream stream = new PrintStream(out)
share|improve this answer
and if i want my function to print it on the screen? how to do it "dynamically"? –  Helgus Feb 27 '12 at 14:18
I don't understand the "dynamically" part. If you want to print to the screen, then use System.out, it's a PrintStream object. –  Florent Guillaume Feb 27 '12 at 14:26

Your Answer


