How to convert an OutputStream to a Writer in Java?


An OutputStream class is a byte-oriented whereas Writer class is a character-oriented. We can convert an OutputStream class to a Writer class using an OutputStreamWriter class and pass an argument of ByteArrayOutputStream object to OutputStreamWriter constructor.

An OutputStreamWriter is a bridge from a character stream to a byte stream, the characters written to it are encoded into bytes using a specified charset.

Syntax

public class OutputStreamWriter extends Writer

Example

import java.io.*;
public class OutputStreamToWriterTest {
   public static void main(String[] args) throws Exception {
      String str = "TUTORIALSPOINT";
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      OutputStreamWriter osw = new OutputStreamWriter(baos);
      for (int i=0; i < str.length(); i++) {
         osw.write((int) str.charAt(i));
      }
      osw.close();
      byte[] b = baos.toByteArray();
      for (int j=0; j < b.length; j++) {
         System.out.println(b[j]);
      }
   }
}

Output

84
85
84
79
82
73
65
76
83
80
79
73
78
84

Updated on: 24-Nov-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements