如何在Java中将OutputStream转换为Writer?
一个的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 < 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
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短