1

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.

arogachev
  • 33,150
  • 7
  • 114
  • 117
Helgus
  • 177
  • 3
  • 7
  • 17

4 Answers4

4

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

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

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!

Community
  • 1
  • 1
aviad
  • 8,229
  • 9
  • 50
  • 98
  • 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
0

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)
Florent Guillaume
  • 8,243
  • 1
  • 24
  • 25
0

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

rascio
  • 8,968
  • 19
  • 68
  • 108