转换流

转换流提供了在字节流和字符流之间的转换

Java API提供了两个转换流:

  • InputStreamReader:将InputStream转换为Reader
  • OutputStreamWriter:将Writer转换为OutputStream

常见的应用场景有:

  • 文件字符编码的转码
  • 读取指定编码的文本文件
// 读取gdk编码的文本文件,使用utf-8读取
public static void readFromGBK (File file) throws IOException {
    FileInputStream fis = null;
    InputStreamReader isr = null;

    try {
        fis = new FileInputStream(file);
        isr = new InputStreamReader(fis, "GBK");

        int len;
        char[] chars = new char[1024];
        while ((len = isr.read(chars)) > -1) {
            String str = new String(chars, 0, len);
            System.out.println(str);
        }
    } catch (IOException e) {
        throw e;
    } finally {
        if (isr != null) {
            isr.close();
        }
    }
}

// 修改文件编码,将utf-8文件修改为gbk编码文件
try (
    InputStreamReader isr  = new InputStreamReader(new FileInputStream("dir/1.txt"), "utf-8");
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("dir/1_gbk.txt"), "gbk")
)
{
    char[] chars = new char[1024];
    int len;

    while ((len = isr.read(chars)) > -1) {
        osw.write(chars, 0, len);
    }
} catch (IOException e) {
    e.printStackTrace();
}
Posted in: IO