OutputStream เป็น byte-oriented ส่วน Writer เป็น character-oriented สามารถแปลง OutputStream เป็น Writer ได้ด้วยคลาส OutputStreamWriter ส่ง argument ByteArrayOutputStream object ให้ constructor ของ OutputStreamWriter OutputStreamWriter เป็นสะพานจาก character stream ไป byte stream ตัวอักษรที่เขียนจะ encode เป็น bytes ด้วย charset ที่กำหนด
ไวยากรณ์
public class OutputStreamWriter extends Writer
ตัวอย่าง
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]);
}
}
}
ผลลัพธ์
84 85 84 79 82 73 65 76 83 80 79 73 78 84