温故知新 流(字节流与字符流)

 

public class OutputStreamAndInputStream {
/*
* 字节流与字符流间转换来实现文本的读与写
* 注意:以Stream结尾的都是字节流
* 一:读取文件
* 1,获取文件File对象
* 2,导入到InputStream中(字节流),向上造型用FileInputStream()
* 3,导入到InputStreamReader中(字节流){注意让中文不能乱码new InputStreamWriter(is, "utf-8");}
* 4,导入到buffrerdReader中(字符流)
* 5,buffrerdReader 每次读取一行,把这一行数据保存字符串中(readLine())
* 6,关闭流
* 二:
*1,创建文本对象File
*2,导出OutputStream,向上造型用FileOutputStream()
*3,导出OutPutStreamWriter,{注意让中文不能乱码new----OutputStreamWriter(os, "utf-8");}
*4,导出到BufferedWriter
*5,BufferedWriter写入内容 write("xxxx");
*6,关闭流
*/

public static void main(String[] args) throws IOException {

//写
File file =new File("book.txt");
OutputStream os=new FileOutputStream(file);//字节流
OutputStreamWriter writer=new OutputStreamWriter(os);//字节流
BufferedWriter bw=new BufferedWriter(writer);//字符流
bw.write("一夜笛声瑟寒流,半窗皓月泻松岗!");
bw.close();
writer.close();
os.close();
//读
file =new File("book.txt");
InputStream is=new FileInputStream(file);//字节流
InputStreamReader reader=new InputStreamReader(is,"utf-8");//字节流
BufferedReader br=new BufferedReader(reader);//字符流
String s="";
while((s=br.readLine())!=null) {
System.out.println(s);
}
br.close();
reader.close();
is.close();
}

}

posted @ 2020-03-24 14:22  唯恐不及  阅读(141)  评论(0编辑  收藏  举报