InputStreamReader/OutputStreamWriter用来实现将字节流转化成字符流。
通过转换流解决乱码
public class TestInputStreamReader {
public static void main(String[] args){
//创建文件字节流输入流对象
try(FileInputStream fis = new FileInputStream("d:/a.txt");
//创建转换流(字节到字符的转换)流对象,并在流对象中指定编码
InputStreamReader isr = new InputStreamReader(fis,"gbk")
){
StringBuilder sb = new StringBuilder();
//操作流对象
int temp = 0;
while((temp = isr.read()) != -1){
sb.append((char)temp);
}
System.out.println();
}catch(IOException e){
e.printStackTrace();
}
}
}
通过转换流实现键盘输入屏幕输出
import java.io.*;
public class TestConvertStream {
public static void main(String[] args){
//创建字符输入和输出流:使用转换流将字节流转换成字符流
BufferedReader br = null;
BufferedWriter bw = null;
try{
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
//使用字符输入和输出流
String str = br.readLine();
//一直读取,直到用户输入了exit为止
while(!"exit".equals(str)){
//写到控制台
bw.write(str);
bw.newLine(); //写一行后换行
bw.flush(); //手动刷新
//再读一行
str = br.readLine();
}
}catch(IOException e){
e.printStackTrace()
}finally{
//关闭字符输入和输出流
if(br != null){
try{
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(bw != null){
try{
bw.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}