How can I create class that takes an implentation of OutputStream
and writes the the content to it?
For example, the following print method is wrong and will not compile. What are the options or better techniques?
public class FooBarPrinter{
private OutputStream o;
public FooBarPrinter(OutputStream o){
this.o=o;
}
public void print(String s){
o.write(s);
}
}
Best Answer
A generic
OutputStream
doesn't have the ability to write aString
directly to it. Instead, you need to get thebyte[]
of theString
and then write them out to the stream.Refer to the OutputStream java documentation for more information on the supported write data types.
My suggestion for making this better is to make sure the
OutputStream
you provide in the constructor is aBufferedOutputStream
, as this will improve the performance of your code. It works by buffering some of the data in memory, and writing it out to disk in big chunks instead of many smaller writes.Here is the java documentation for BufferedOutputStream