Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to write a String to OutputStream in Java

I have an OutputStream instance which return from HttpURLConnection. I need to write a UTF-8 String into the stream.

I have 2 ways:

  1. Use OutputStream itself

    // write String
    os.write("some utf8 text".getBytes(Charsets.UTF_8));
    
  2. 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!

like image 567
Loc Avatar asked Jun 17 '16 19:06

Loc


People also ask

How do you write OutputStream to string?

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.

How do I write a OutputStream file?

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.

How do you declare an OutputStream in Java?

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.

Can we convert string to stream in Java?

We can convert a String to an InputStream object by using the ByteArrayInputStream class. The ByteArrayInputStream is a subclass present in InputStream class.


1 Answers

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.

like image 58
Nicolas Filotto Avatar answered Sep 29 '22 02:09

Nicolas Filotto