21.4 转换流(重点掌握)

字节流转字符流,称作转换流,包括:

  1. InputStreamReader—> 将字节流转换为字符流。是字节流通向字符流的桥梁。如果不指定字符集编码,该解码过程将使用平台默认的字符编码,如:GBK/UTF-8。

  2. OutputStreamWriter—> 将字节流转换为字符流。是字节流通向字符流的桥梁。如果不指定字符集编码,该解码过程将使用平台默认的字符编码,如:GBK/UTF-8。

21.4.1 InputStreamReader的构造方法

  1. InputStreamReader(InputStream in);//构造一个默认编码集的InputStreamReader类。

  2. InputStreamReader(InputStream in,String charsetName);构造一个指定编码集的InputStreamReader类。

21.4.2 InputStreamReader的使用

try {
    File file = new File("test.txt");
    FileInputStream fis = new FileInputStream(file);
    InputStreamReader isr = new InputStreamReader(fis);
    int read = isr.read();
      //char cbuf[]=new char[512];
    //isr.read(cbuf);
    System.out.println((char)read);
    isr.close();
}...
File file = new File("a.txt");
try {
  InputStreamReader isr1 = new FileReader(file);
  // FileReader(file)源码
  // public FileReader(File file) throws FileNotFoundException {
  // super(new FileInputStream(file));
  // }

  FileInputStream fis = new FileInputStream(file);
  // 根据utf-8编码,将字节流转换为字符流
  InputStreamReader isr = new InputStreamReader(fis);
  // 使用缓冲流装饰InputStreamReader
  BufferedReader br = new BufferedReader(isr);

  br.close();
} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

21.4.3 OutputStreamWriter的构造方法

  1. OutputStreamWriter(OutputStream out);构造一个默认编码集的OutputStreamWriter类

  2. OutputStreamWriter(OutputStream out,String charsetName);构造一个指定编码集的OutputStreamWriter类。

21.4.4 OutputStreamWriter的使用

try {
    File file = new File("test.txt");
    FileOutputStream fos = new FileOutputStream(file);
    OutputStreamWriter osw = new OutputStreamWriter(fos);
    String str="育知同创";
    osw.write(str);//直接写入字符串
    //osw.write(str.toCharArray());//写入 char 数组
    osw.flush();
    osw.close();
}...
File file = new File("a.txt");
try {
  OutputStreamWriter osw1= new FileWriter(file);

  FileOutputStream fos = new FileOutputStream(file);
  OutputStreamWriter osw = new OutputStreamWriter(fos);
  BufferedWriter bw = new BufferedWriter(osw);

  osw1.close();
  bw.close();
} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

results matching ""

    No results matching ""