Java 之 转换流

一、字符编码和字符集

  字符编码与字符集

二、编码引发的问题

  当我们使用 UTF-8 编码保存文件时,用 UTF-8 再次读取不会出现任何问题。但是,当使用其他的编码(如GBK)读取文件时,就会出现乱码现象。

  Demo:

 1 public class ReaderDemo {
 2     public static void main(String[] args) throws IOException {
 3         FileReader fileReader = new FileReader("E:\File_GBK.txt");
 4         int read;
 5         while ((read = fileReader.read()) != ‐1) {
 6             System.out.print((char)read);
 7         }
 8          fileReader.close();
 9     }
10 } 
11 输出结果:
12 ���    

三、转换流理解图解

  转换流是字节与字符间的桥梁!

 

   转换流的原理

四、InputStreamReader类

五、OutputStreamWriter类

六、转换文件编码

  要求:GBK编码的文本文件,转换为UTF-8编码的文本文件。
  代码实现:

 1 /*
 2     分析:
 3         1.创建InputStreamReader对象,构造方法中传递字节输入流和指定的编码表名称GBK
 4         2.创建OutputStreamWriter对象,构造方法中传递字节输出流和指定的编码表名称UTF-8
 5         3.使用InputStreamReader对象中的方法read读取文件
 6         4.使用OutputStreamWriter对象中的方法write,把读取的数据写入到文件中
 7         5.释放资源
 8  */
 9  public static void main(String[] args) throws IOException {
10         //1.创建InputStreamReader对象,构造方法中传递字节输入流和指定的编码表名称GBK
11         InputStreamReader isr = new InputStreamReader(new FileInputStream("E:\我是GBK格式的文本.txt"),"GBK");
12         //2.创建OutputStreamWriter对象,构造方法中传递字节输出流和指定的编码表名称UTF-8
13         OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("E:\我是utf_8格式的文件.txt"),"UTF-8");
14         //3.使用InputStreamReader对象中的方法read读取文件
15         int len = 0;
16         while((len = isr.read())!=-1){
17             //4.使用OutputStreamWriter对象中的方法write,把读取的数据写入到文件中
18             osw.write(len);
19         }
20         //5.释放资源
21         osw.close();
22         isr.close();
23     }
原文地址:https://www.cnblogs.com/niujifei/p/11497539.html