Java IO流转换流

InputStreamReader :是字节流通向字符流的桥梁,它使用指定的 charset 读取字节并将其解码为字符。

 

OutputStreamWriter  :是字符流通向字节流的桥梁,可使用指定的 charset 将要写入流中的字符编码成字节。

 

InputStreamReader

构造方法

InputStreamReader(InputStream in)
创建一个使用默认字符集的 InputStreamReader

InputStreamReader(InputStream in, Charset cs)
创建使用给定字符集的 InputStreamReader

InputStreamReader(InputStream in, CharsetDecoder dec)
创建使用给定字符集解码器的 InputStreamReader

InputStreamReader(InputStream in, String charsetName)
创建使用指定字符集的 InputStreamReader

OutputStreamWriter

构造方法

OutputStreamWriter(OutputStream out)
创建使用默认字符编码的 OutputStreamWriter

OutputStreamWriter(OutputStream out, Charset cs)
创建使用给定字符集的 OutputStreamWriter

OutputStreamWriter(OutputStream out, CharsetEncoder enc)
创建使用给定字符集编码器的 OutputStreamWriter

OutputStreamWriter(OutputStream out, String charsetName)
创建使用指定字符集的 OutputStreamWriter

 

  BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\char.txt")));
      bufw.write("你在做什么");
      bufw.close();
      BufferedReader bufr=new BufferedReader(new InputStreamReader(new FileInputStream("C:\\demo.txt")));
      String line=bufr.readLine();
      System.out.println(line);

4,例:获取用户键盘录入的数据,并将数据变成大写显示在控制台上。如果用户输入的over,结束键盘录入。

TransStreamDemo.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class TransStreamDemo {
   public static void main(String[] args) throws IOException {
      method_2();
   }

   // 字节转字符
   public static void method_1() throws IOException {
      InputStream in = System.in;
      InputStreamReader isr = new InputStreamReader(in);
      BufferedReader bufr = new BufferedReader(isr);
      String line = null;
      while ((line = bufr.readLine()) != null) {
         if ("over".equals(line))
            break;
         System.out.println(line.toUpperCase());
      }
   }
   // 字节转字符,字符转字节
   public static void method_2() throws IOException {
      // InputStream in = System.in;
      // InputStreamReader isr = new InputStreamReader(in);
      // BufferedReader bufr = new BufferedReader(isr);
      // 简写
      BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
      // OutputStream out = System.out;
      // OutputStreamWriter osw = new OutputStreamWriter(out);
      // BufferedWriter bufw = new BufferedWriter(osw);
      // 简写
      BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter( System.out));
      String line = null;
      while ((line = bufr.readLine()) != null) {
         if ("over".equals(line))
            break;
         bufw.write(line.toUpperCase());
         bufw.newLine();
         bufw.flush();
      }
   }
}

转换图解

 BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\char.txt")));
bufw.write("你在做什么");
bufw.close();