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.
We can convert a String to an InputStream object by using the ByteArrayInputStream class. The ByteArrayInputStream is a subclass present in InputStream class. In ByteArrayInputStream there is an internal buffer present that contains bytes that reads from the stream.
So you can get the OutputStream from that method as : OutputStream os = ClassName. decryptAsStream(inputStream,encryptionKey); And then use the os .
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();
}
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.
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With