Java OutputStream – How to Write Strings

javaoutputstreamstring

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 a String directly to it. Instead, you need to get the byte[] of the String and then write them out to the stream.

public void print(String s){ 
    o.write(s.getBytes());
}

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 a BufferedOutputStream, 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

Related Question