转换流
InputStreamReader/InputStreamWriter:是字节流与字符流之间的桥梁。能将字节流转换为字符流,并且能为字节流指定字符集进行编码/解码,可处理一个个的字符(例如System.in和System.out都涉及到转换流)
举例1
1、InputStreamReader和OutputStreamWriter用来控制字节和字符的转换
2、BufferedReader是更方便的操作
public static void main(String[] args) {
//操作System.in和System.out
try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out))){
//循环获取键盘的输入,输出此内容(exit退出)
String msg = "";
while(!msg.equals("exit"))
{
msg = reader.readLine(); //循环读取
writer.write(msg); //循环写出,当达到内部缓冲容量的时候才能写出,如果内容太少可以强制刷新
writer.newLine();
writer.flush(); //强制刷新
}
}catch(IOException e)
{
e.printStackTrace();
}
}
举例2:对网络流进行操作下载百度源码(设计字符集)
public class ConvertFlow2 {
public static void main(String[] args) {
test();
}
public static void test() {
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new URL("http://www.baidu.com").openStream(),"utf-8"))){
String msg = "";
while((msg=reader.readLine())!=null)
{
System.out.println(msg);
}
}catch(IOException e)
{
e.printStackTrace();
}
}
public static void test02() {
try(InputStreamReader is = new InputStreamReader(new URL("http://www.baidu.com").openStream(),"utf-8");)
{
int tmp;
while((tmp=is.read())!=-1)
{
System.out.print((char)tmp);
if(tmp=='>')
{
System.out.println();
}
}
}catch(IOException e)
{
e.printStackTrace();
}
}