Java IO转换流的编码解码

需求5:将一个中文字符串按照指定的编码表写入到一个文本文件中。

 

注意:既然需求中已经明确了指定编码表的动作,那就不可以调用FileWriter,因为FileWriter内部是使用的默认的本地编码表,只能使用其父类。OutputStreamWriter

 

TransStreamTest1.java

import java.io.*;

class TransStreamTest1 {
   public static void main(String args[]) throws IOException {
      writeText_1();
      writeText_2();
      readText();
   }

   public static void readText() throws IOException {
      FileInputStream fr = new FileInputStream("G:\\utf_8.txt");
      InputStreamReader isr = new InputStreamReader(fr, "utf-8");
      char chs[] = new char[10];
      int len = isr.read(chs);
      System.out.println(new String(chs, 0, len));
   }

   public static void writeText_1() throws IOException {
      FileWriter fw = new FileWriter("G://gbk_1.txt");
      fw.write("你好");
      fw.close();
   }

   public static void writeText_2() throws IOException {
      FileOutputStream fos = new FileOutputStream("G:\\utf_8.txt");
      OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
      osw.write("你好");
      osw.close();
   }
}