InputStreamReader和 OutputStreamWriter

new InputStreamReader(字节流,"UTF-8") //指定模式

将字节流转换为字符流,方便处理,比如能使用BufferedReader处理流
可以处理字符集:InputStreamReader isr=new InputStreamReader(字节流,"UTF-8");
网络流:new URL("http://www.baidu.com").openStream(),这是一个字节流
用装饰器装饰转换流转换成的字符流:BufferedReader reader=new BufferedReader(new InputStreamReader(new URL("http://www.baidu.com").openStream(),"UTF-8"))

用转换流来读取键盘输入输出的字节流:

try(BufferedReader isr=new BufferedReader( new InputStreamReader(System.in)); BufferedWriter osw=new BufferedWriter(new OutputStreamWriter(System.out));){ //键盘循环读取,exit退出 String s=" "; while(!s.equals("exit")) { s=isr.readLine(); //按行读取 osw.write(s); //写出 osw.newLine(); osw.flush(); //强制刷新,因为数据太小无法输出,要满足一定kb才会自动输出 } } catch(IOException e) { System.out.println("操作异常"); }

操作网络流,读取百度源码:

使用装饰器:

//使用转换流,读取中文不会乱码 try(BufferedReader reader=new BufferedReader(new InputStreamReader(new URL("http://www.baidu.com").openStream(),"UTF-8")); ){ //网页的字符集是utf-8 //读取 String s; while((s=reader.readLine())!=null) { System.out.println(s); } } catch(IOException e) { System.out.println("操作异常"); }}

不使用装饰器:

try(InputStreamReader is=new InputStreamReader(new URL("http://www.baidu.com").openStream()); ){ //读取 int len; while((len=is.read())!=-1) { System.out.print((char)len); } } catch(IOException e) { System.out.println("操作异常"); }