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