OutputStream là lớp byte-oriented trong khi Writer là character-oriented. Chuyển đổi OutputStream sang Writer dùng OutputStreamWriter và truyền đối tượng ByteArrayOutputStream cho constructor. OutputStreamWriter là cầu nối từ character stream sang byte stream, ký tự ghi vào được encode thành byte bằng charset chỉ định.
Cú pháp
public class OutputStreamWriter extends Writer
Ví dụ
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]);
}
}
}
Kết quả
84 85 84 79 82 73 65 76 83 80 79 73 78 84