一、概念
------->1、BufferedReader/BufferedWriter 【参考19.03.31文章】
*Reader/Writer-------->2、InputStreamReader/ OutputStreamWriter(转换流,实现字节转字符)---》2-1:FileReader和FileWriter(文件字符类【19.03.31文章】)
【代码示例】
/**字符流相关
* 2、InputStreamReader/ OutputStreamWriter(转换流,实现字节转字符)》》2-1:FileReader和FileWriter(用过,文件字符类)
* 要点:
* 1)、以字符流的形式操作字节流(仅限纯文本)
* 2)、指定字符集
*
*
*/
package cn.sxt.test; import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.URI;
import java.net.URL; public class Test_0402_InputStreamReader {//System.in 字节输入流 , System.out字节输出流
public static void main(String[] args) throws IOException {
/*InputStreamReader isr=new InputStreamReader(System.in);//控制台输入,通过这步字节已经转成字符了
BufferedReader bReader=new BufferedReader(isr);//加个缓冲字符流 OutputStreamWriter osr=new OutputStreamWriter(System.out);//控制台输出
BufferedWriter bWriter=new BufferedWriter(osr); //基本操作,循环获取键盘的输入(输入"exit"退出循环),输出此内容
String msg="";
while (!msg.equals("exit")) {
msg=bReader.readLine();//逐行循环读取
bWriter.write(msg);//逐行循环写出
bWriter.newLine();//换行
bWriter.flush();//强制刷新,即使缓冲区没满,也可以让缓冲区的内容强制出去。如果没这句只有缓冲区满才会输出
}
bReader.close();
bWriter.close(); */ //抓取baidu首页网页的源码
URL url=new URL("http://www.baidu.com"); //url.openStream() 获得一个网络字节流
InputStreamReader isr=new InputStreamReader(url.openStream(),"UTF-8");//通过这步字节已经转成字符了
BufferedReader bReader=new BufferedReader(isr); FileOutputStream file =new FileOutputStream("baidu.html");
OutputStreamWriter osr=new OutputStreamWriter(file,"UTF-8");//把读取到的保存在baidu.html文件中去
BufferedWriter bWriter=new BufferedWriter(osr); String msg=null;
while ((msg=bReader.readLine())!=null) {
//System.out.println(msg);
bWriter.write(msg);
bWriter.newLine();
}
bWriter.flush(); bReader.close();
bWriter.close();
} }