I have an OutputStream instance which return from HttpURLConnection. I need to write a UTF-8 String into the stream.
I have 2 ways:
Use OutputStream itself
// write String
os.write("some utf8 text".getBytes(Charsets.UTF_8));
Use OutputStreamWriter wrapper
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, CharsetUtils.UTF_8));
OutputStreamWriter osw = new OutputStreamWriter(os, CharsetUtils.UTF_8);
osw.write("some utf8 text");
Question: Why should we use OutputStreamWriter over OutputStream to write String?
Thanks!
Example: Convert OutputStream to String This is done using stream's write() method. Then, we simply convert the OutputStream to finalString using String 's constructor which takes byte array. For this, we use stream's toByteArray() method.
Steps to write data to a file using FileOutputStream:FileOutputStream fout = new FileOutputStream(“file1. txt”); This will enable us to write data to the file.
Methods of OutputStreamwrite() - writes the specified byte to the output stream. write(byte[] array) - writes the bytes from the specified array to the output stream. flush() - forces to write all data present in output stream to the destination. close() - closes the output stream.
We can convert a String to an InputStream object by using the ByteArrayInputStream class. The ByteArrayInputStream is a subclass present in InputStream class.
Question: Why should we use OutputStreamWriter over OutputStream to write String?
Simply to define the encoding only once in the constructor of OutputStreamWriter instead of specifying each time we want to encode a String into UTF-8 thanks to getBytes(Charsets.UTF_8)
Moreover an OutputStreamWriter provides many convenient methods to write String such as write(String), write(String, int, int), append(CharSequence) and append(CharSequence, int, int) that you don't have in an OutputStream.
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