Write string to output stream

I have several output listeners that are implementing OutputStream . It can be either a PrintStream writing to stdout or to a File, or it can be writing to memory or any other output destination; therefore, I specified OutputStream as (an) argument in the method. Now, I have received the String . What is the best way to write to streams here? Should I just use Writer.write(message.getBytes()) ? I can give it bytes, but if the destination stream is a character stream then will it convert automatically? Do I need to use some bridge streams here instead?

307k 59 59 gold badges 562 562 silver badges 617 617 bronze badges asked Nov 1, 2010 at 12:54 7,755 12 12 gold badges 38 38 silver badges 37 37 bronze badges

I am not sure but this sounds like you are trying to reinvent the wheel here, have you looked through the Java Base API, as well as Commons IO API?

Commented Nov 1, 2010 at 12:57

6 Answers 6

Streams ( InputStream and OutputStream ) transfer binary data. If you want to write a string to a stream, you must first convert it to bytes, or in other words encode it. You can do that manually (as you suggest) using the String.getBytes(Charset) method, but you should avoid the String.getBytes() method, because that uses the default encoding of the JVM, which can't be reliably predicted in a portable way.

The usual way to write character data to a stream, though, is to wrap the stream in a Writer , (often a PrintWriter ), that does the conversion for you when you call its write(String) (or print(String) ) method. The corresponding wrapper for InputStreams is a Reader.

PrintStream is a special OutputStream implementation in the sense that it also contain methods that automatically encode strings (it uses a writer internally). But it is still a stream. You can safely wrap your stream with a writer no matter if it is a PrintStream or some other stream implementation. There is no danger of double encoding.

Example of PrintWriter with OutputStream:

try (PrintWriter p = new PrintWriter(new FileOutputStream("output-text.txt", true))) < p.println("Hello"); >catch (FileNotFoundException e1)