Converting an OutputStream to a Writer

An OutputStream is byte oriented. A Writer is Character oriented. To hook up an OutputStream to a Writer and have the conversion done automatically for you, use the class OutputStreamWriter.

Main.java:

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

outputs:

65
66
67