转换流:都是字节流转向字符流
InputStreamReader
OutputStreamWriter
转换流的作用:
- 可以把字节流转换成字符流。
- 可以指定任意的码表进行读写数据。
FileReader---------- 默认gbk
FileWriter ---------默认gbk
***疑问:
为什么读取数据或写入数据的时候不直接使用BufferedReader/BufferedWriter呢? ***
除了上面可以指定码表的功能外,还有一个原因就是好有的函数返回的就是字节流,或者一些第三方框架就是使用的字节流,这个是我们没有办法改变的; 当时我们在读写数据的时候又希望使用字符流,所以诞生了这个转换流
public class Demo3 {
public static void main(String[] args) throws IOException {
// readTest1();
// writeTest1();
// writeData();
readData();
}
//指定码表读取数据
public static void readData() throws IOException{
FileInputStream fileInputStream = new FileInputStream("F:\\a.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"utf-8");
char[] buf = new char[1024];
int length = 0 ;
while((length = inputStreamReader.read(buf))!=-1){
System.out.println(new String(buf,0,length));
}
//关闭资源
inputStreamReader.close();
}
//指定码表进行写数据
public static void writeData() throws IOException{
FileOutputStream fileOutputStream = new FileOutputStream("f:\\a.txt"); // FileWriter 默认使用的码表是gbk码表,而且不能指定码表写。
OutputStreamWriter fileWriter = new OutputStreamWriter(fileOutputStream, "utf-8");
fileWriter.write("中国");
fileWriter.close();
}
//把输出字节流转换成输出字符流
public static void writeTest1() throws IOException{
FileOutputStream fileOutputStream = new FileOutputStream("f:\\a.txt");
String data = "hello world";
//需求:要把输出字节流转换成输出字符流. //字节流向文件输出数据的时候需要借助String类的getbyte功能,我想使用字符流.
OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream);
//写出数据
writer.write(data);
//关闭资源
writer.close();
}
//把输入字节流转换成了输入字符流 -----> InputStreamReader
public static void readTest1() throws IOException{
//先获取标准 的输入流
InputStream in = System.in;
//把字节流转换成字符流
InputStreamReader inputStreamReader = new InputStreamReader(in);
//一次读取一行的功能
// BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line = bufferedReader.readLine())!=null){
System.out.println(line);
}
}
}