InputStreamReader转换输入流
OutputStreamWriter转换输出流
转换流属于字符流,用于包装基本流。是字符流和字节流之间的桥梁。
作用1:指定字符集读写。(JDK11版本之后淘汰了,了解就行)
作用2:字节流想要使用字符流中的方法。
练习转换流的使用:
public class ConvertStreamDemo1 {
public static void main(String[] args) throws IOException {
/*
利用转换流按照指定字符编码读取(了解)
因为JDK11:这种方式被淘汰了。替代方案(掌握)
F:\JavaSE最新版\day29-IO(其他流)\资料\gbkfile.txt
*/
/* //1.创建对象并指定字符编码
InputStreamReader isr = new InputStreamReader(new FileInputStream("myio\\gbkfile.txt"),"GBK");
//2.读取数据
int ch;
while ((ch = isr.read()) != -1){
System.out.print((char)ch);
}
//3.释放资源
isr.close();*/
FileReader fr = new FileReader("myio\\gbkfile.txt", Charset.forName("GBK"));
//2.读取数据
int ch;
while ((ch = fr.read()) != -1){
System.out.print((char)ch);
}
//3.释放资源
fr.close();
}
}
public class ConvertStreamDemo2 {
public static void main(String[] args) throws IOException {
/*
利用转换流按照指定字符编码写出
*/
/*
//1.创建转换流的对象
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("myio\\b.txt"),"GBK");
//2.写出数据
osw.write("你好你好");
//3.释放资源
osw.close();*/
FileWriter fw = new FileWriter("myio\\c.txt", Charset.forName("GBK"));
fw.write("你好你好");
fw.close();
}
}
public class ConvertStreamDemo3 {
public static void main(String[] args) throws IOException {
/*
将本地文件中的GBK文件,转成UTF-8
*/
//1.JDK11以前的方案
/* InputStreamReader isr = new InputStreamReader(new FileInputStream("myio\\b.txt"),"GBK");
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("myio\\d.txt"),"UTF-8");
int b;
while((b = isr.read()) != -1){
osw.write(b);
}
osw.close();
isr.close();*/
//2.替代方案
FileReader fr = new FileReader("myio\\b.txt", Charset.forName("GBK"));
FileWriter fw = new FileWriter("myio\\e.txt",Charset.forName("UTF-8"));
int b;
while ((b = fr.read()) != -1){
fw.write(b);
}
fw.close();
fr.close();
}
}
public class ConvertStreamDemo4 {
public static void main(String[] args) throws IOException {
/*
利用字节流读取文件中的数据,每次读一整行,而且不能出现乱码
//1.字节流在读取中文的时候,是会出现乱码的,但是字符流可以搞定
//2.字节流里面是没有读一整行的方法的,只有字符缓冲流才能搞定
*/
/* FileInputStream fis = new FileInputStream("myio\\a.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
System.out.println(str);
br.close();*/
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("myio\\a.txt")));
String line;
while ((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
}
}