I mean if I've 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 preferably be a String
variable).
The question is, how it will dynamically determine the output 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.
4 Answers
I think you're looking for java.lang.System#setOut(PrintStream stream) method. Which essentially lets you reassign the standard output stream programmatically.

- 761,203
- 64
- 569
- 643
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.lang.Object
java.io.Console (implements java.io.Flushable)
java.io.File (implements java.lang.Comparable<T>, java.io.Serializable)
java.io.FileDescriptor
java.io.InputStream (implements java.io.Closeable)
java.io.ByteArrayInputStream
java.io.FileInputStream
java.io.FilterInputStream
java.io.BufferedInputStream
java.io.DataInputStream (implements java.io.DataInput)
Good Luck!
-
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)

- 8,243
- 1
- 24
- 25
-
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
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

- 8,968
- 19
- 68
- 108