一个的OutputStream类是面向字节的,而作家类是面向字符的。我们可以使用一个OutputStream类转换为Writer类OutputStreamWriter类和传递的参数ByteArrayOutputStream对象OutputStreamWriter构造。一个OutputStreamWriter是从字符流以字节流的桥梁,写入到它的字符被编码成使用指定的charset字节。
语法public class OutputStreamWriter extends Writer
示例import java.io.*;
public class OutputStreamToWriterTest {
public static void main(String[] args) throws Exception {
String str = "nhooo";
ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(baos); for (int i=0; i
osw.write((int) str.charAt(i));
}
osw.close();
byte[] b = baos.toByteArray();
for (int j=0; j
System.out.println(b[j]);
}
}
}
输出结果84
85
84
79
82
73
65
76
83
80
79
73
78
84