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!

Share:
11,251
Helgus
Author by

Helgus

Updated on June 04, 2022

Comments

  • Helgus
    Helgus almost 2 years

    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.

  • Helgus
    Helgus about 12 years
    and if i want my function to print it on the screen? how to do it "dynamically"?
  • Helgus
    Helgus about 12 years
    it describes only File io, but i need another way of implementation
  • Florent Guillaume
    Florent Guillaume about 12 years
    I don't understand the "dynamically" part. If you want to print to the screen, then use System.out, it's a PrintStream object.
  • aviad
    aviad about 12 years
    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.