java中的OutputStreamWriter用法

这是我找到的资料:“OutputStreamWriter:是Writer的子类,将输出的字符流变为字节流,即将一个字符流的输出对象变为字节流输出对象。”
但是public OutputStreamWriter(OutputStream out)

传入的参数又是字节流的,岂不是还是把字节流变成字符流吗?
和资料矛盾了,求解答

是把将输出的字符流变为字节流,这算是一个中间类。需要包装,比如

Writer out = new BufferedWriter(new OutputStreamWriter(System.out));

就是将BUfferedWriter输出所要求的字符流,由OutputStreamWriter将字符和字节作为一个转换,你自己想反了。具体请看Java的API文档上的说明。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-10-18
  InputStreamReader 将字节流转换为字符流。是字节流通向字符流的桥梁。如果不指定字符集编码,该解码过程将使用平台默认的字符编码;
例如:
public static void transReadNoBuf() throws IOException {
/**
* 没有缓冲区,只能使用read()方法。
*/
//读取字节流
// InputStream in = System.in;//读取键盘的输入。
InputStream in = new FileInputStream("D:\\demo.txt");//读取文件的数据。
//将字节流向字符流的转换。要启用从字节到字符的有效转换,可以提前从底层流读取更多的字节.
InputStreamReader isr = new InputStreamReader(in);//读取
// InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\demo.txt"));//综合到一句。

char []cha = new char[1024];
int len = isr.read(cha);
System.out.println(new String(cha,0,len));
isr.close();

}
public static void transReadByBuf() throws IOException {
/**
* 使用缓冲区 可以使用缓冲区对象的 read() 和 readLine()方法。
*/
//读取字节流
// InputStream in = System.in;//读取键盘上的数据
InputStream in = new FileInputStream("D:\\demo.txt");//读取文件上的数据。
//将字节流向字符流的转换。
InputStreamReader isr = new InputStreamReader(in);//读取
//创建字符流缓冲区
BufferedReader bufr = new BufferedReader(isr);//缓冲
// BufferedReader bufr = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\demo.txt")));可以综合到一句。
/* int ch =0;
ch = bufr.read();
System.out.println((char)ch);*/
String line = null;
while((line = bufr.readLine())!=null){
System.out.println(line);
}
isr.close();
}
相似回答