IO OutputStreamWriter和InputStreamReader

因为FileWriter和FileReader构造方法都是声明: 假定默认字符编码GBK和默认字节缓冲区大小都是可接受的。要自己指定这些值,可以先在 FileOutputStream 上构造一个 OutputStreamWriter,所以如果想改变读取或者写入某文件的编码方式,需要用到OutputStreamWriter和InputStreamReader。

OutputStreamWriter

  是字符流通向字节流的桥梁:使用指定的 charset 将要向其写入的字符编码为字节。它使用的字符集可以由名称指定或显式给定,否则可能接受平台默认的字符集。每次调用 write() 方法都会针对给定的字符(或字符集)调用编码转换器。在写入基础输出流之前,得到的这些字节会在缓冲区累积。可以指定此缓冲区的大小,不过,默认的缓冲区对多数用途来说已足够大。注意,传递到此 write() 方法的字符是未缓冲的。为了达到最高效率,可考虑将 OutputStreamWriter 包装到 BufferedWriter 中以避免频繁调用转换器。

构造函数

  OutputStreamWriter(OutputStream out) 创建使用默认字符编码的 OutputStreamWriter。 
  OutputStreamWriter(OutputStream out, Charset cs) 创建使用给定字符集的 OutputStreamWriter。 
  OutputStreamWriter(OutputStream out, CharsetEncoder enc) 创建使用给定字符集编码器的 OutputStreamWriter。 
  OutputStreamWriter(OutputStream out, String charsetName) 创建使用指定字符集的 OutputStreamWriter。charsetName:GBK,UTF-8可选

特有方法

  String getEncoding() 返回此流使用的字符编码的名称

InputStreamReader

  是字节流通向字符流的桥梁:它使用指定的 charset 读取字节并将其解码为字符。它使用的字符集可以由名称指定或显式给定,否则可能接受平台默认的字符集。

每次调用 InputStreamReader 中的一个 read() 方法都会导致从基础输入流读取一个或多个字节。要启用从字节到字符的有效转换,可以提前从基础流读取更多的字节,使其超过满足当前读取操作所需的字节。

构造函数

  InputStreamReader(InputStream in) 创建一个使用默认字符集的 InputStreamReader。 
  InputStreamReader(InputStream in, Charset cs) 创建使用给定字符集的 InputStreamReader。 
  InputStreamReader(InputStream in, CharsetDecoder dec) 创建使用给定字符集解码器的 InputStreamReader。 
  InputStreamReader(InputStream in, String charsetName) 创建使用指定字符集的 InputStreamReader。

特有方法

String getEncoding() 返回此流使用的字符编码的名称。

指定编码读写文件

  windows操作系统默认的是gbk的编码,gbk编码中文时一个中文占2个字节,而utf-8编码时一个中文占3个字节,所以如果用FileReader去读utf-8编码的文件就会出现乱码的情况,因为FileReader读取的编码时默认的操作系统gbk的编码去读取的,而且无法更改编码类型,这时候就要用到InputStreamReader这个转换流了。FileWriter和InputStreamWriter也是这个情况

读文件

public static void readerType() throws IOException{
    FileInputStream fis = new FileInputStream("F:\utf.txt");//utf-8编码的文件
    InputStreamReader isr = new InputStreamReader(fis,"utf-8");
    
    FileInputStream fis = new FileInputStream("F:\gbk.txt");//gbk编码的文件
    InputStreamReader isr = new InputStreamReader(fis);//默认gbk编码
    
    char[] ch = new char[1024];
    
    int len = isr.read(ch);
    
    System.out.println(new String(ch,0,len));
    isr.close();
}

写文件

public static void writerType() throws IOException{
        
    FileOutputStream fos = new FileOutputStream("F:\utf.txt");
    OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
    
    FileOutputStream fos = new FileOutputStream("F:\gbk.txt");
    OutputStreamWriter osw = new OutputStreamWriter(fos);//默认gbk不用指定
    
    osw.write("你好");
    
    osw.close();
}
原文地址:https://www.cnblogs.com/ms-grf/p/7268175.html