How to Set an Output Stream Java
11,251
Solution 1
I think you're looking for java.lang.System#setOut(PrintStream stream) method. Which essentially lets you reassign the standard output stream programmatically.
Solution 2
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!
Author by
Helgus
Updated on June 04, 2022Comments
-
Helgus almost 2 years
I mean if I've to create a method some kind of a:
void setOutputStream(PrintStream stream)
. So thestream
variable is an output stream where I'll write my data(which will preferably be aString
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. -
Helgus about 12 yearsand if i want my function to print it on the screen? how to do it "dynamically"?
-
Helgus about 12 yearsit describes only File io, but i need another way of implementation
-
Florent Guillaume about 12 yearsI don't understand the "dynamically" part. If you want to print to the screen, then use
System.out
, it's aPrintStream
object. -
aviad about 12 yearsThe idea is the same for all java.io.*streams the entire hierarchy implements the Decorator pattern and this is what you need to do.