如何在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 红包祝福语简短10字
18 周六早晨祝福语简短