Write string to output stream
Asked Answered
S

6

165

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?

Siward answered 1/11, 2010 at 12:54 Comment(1)
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?Burushaski
I
167

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) {
    e1.printStackTrace();
}
Impacted answered 1/11, 2010 at 13:5 Comment(2)
So using PrintWriter is just like using String.getBytes(). It uses whatever random encoding that happens to be the default of the JVM. So it only works if you're lucky.Hannie
the code snippet should really be using a constructor that also takes a Charset param, especially given the first paragraph of the answer...Petersen
A
127

OutputStream writes bytes, String provides chars. You need to define Charset to encode string to byte[]:

outputStream.write(string.getBytes(Charset.forName("UTF-8")));

Change UTF-8 to a charset of your choice.

Avera answered 1/11, 2010 at 14:48 Comment(2)
Append with the following line. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();Collum
.getBytes(StandardCharsets.UTF_8) is a little bit cleanerLuminesce
G
35

You can create a PrintStream wrapping around your OutputStream and then just call it's print(String):

final OutputStream os = new FileOutputStream("/tmp/out");
final PrintStream printStream = new PrintStream(os);
printStream.print("String");
printStream.close();
Gi answered 1/11, 2010 at 13:4 Comment(1)
What character set is PrintStream using to convert to bytes?Appolonia
G
30

By design it is to be done this way:

OutputStream out = ...;
try (Writer w = new OutputStreamWriter(out, "UTF-8")) {
    w.write("Hello, World!");
} // or w.close(); //close will auto-flush
Greisen answered 4/11, 2015 at 17:57 Comment(2)
Note that w.close() will close out as well.Plowman
I prefer this answer because it provides an explicit encoding specification! And I recommend using the existing predefined encodings, like StandardCharsets.UTF_8 instead of String literals ("UTF-8").Laddy
S
13

Wrap your OutputStream with a PrintWriter and use the print methods on that class. They take in a String and do the work for you.

Sowens answered 1/11, 2010 at 13:0 Comment(0)
G
9

You may use Apache Commons IO:

try (OutputStream outputStream = ...) {
    IOUtils.write("data", outputStream, "UTF-8");
}
Gallaher answered 8/4, 2016 at 6:52 Comment(1)
IOUtils.write(String data, OutputStream output, Charset encoding) is implemented as output.write(data.getBytes(Charsets.toCharset(encoding))), so it may if an encoded string can't fit in a byte arrayPeacemaker

© 2022 - 2024 — McMap. All rights reserved.