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.
Comments
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!
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)
2 Comments
System.out, it's a PrintStream object.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