2

Java知识点总结(JavaIO-转换流)

@(Java知识点总结)[Java, JavaIO]

[toc]

clipboard.png

OutputStreamWriter

是Writer的子类,将一个字符流的输出对象变为字节流的输出对象。

clipboard.png

clipboard.png

InputStreamReader

是Reader的子类,将一个字节流的输入对象变为字符流的输入对象。

clipboard.png

clipboard.png

public  class Demo05 {
 
  // 将字节输出流转为字符输出流
  public static void test1() throws IOException {
    File file = new File("E:" + File.separator + "test.txt");
    
    Writer out = new OutputStreamWriter(new FileOutputStream(file)); // 字节流转为字符流
    
    out.write("苹果");
    out.close();
 
  }
 
  // 将字节输入流转为字符输入流
  public static void test2() throws IOException {
    File file = new File("E:" + File.separator + "test.txt");
    
    Reader input = new InputStreamReader(new FileInputStream(file));
    char[] c = new char[1024];
    int len = input.read(c);
    
    input.close();
    System.out.println("内容是:" +new String(c,0,len));
  }
 
  public static void main(String[] args) {
    try {
       test1();
       test2();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

苏生
803 声望725 粉丝