全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-08 6 分钟 ✍️ juanwangdev

转换流

转换流将字节流转换为字符流,是字节流和字符流的桥接类。

转换流的作用

核心功能

  • 将字节输入流转换为字符输入流
  • 将字节输出流转换为字符输出流
  • 可以在转换时指定字符编码

解决的问题

  • FileReader/FileWriter使用默认编码,无法指定
  • 不同编码文件读取可能乱码
  • 需要明确指定编码的场景

InputStreamReader

功能

将字节输入流转换为字符输入流(Reader)。

使用方式

Java
// 默认编码
InputStreamReader isr = new InputStreamReader(
    new FileInputStream("test.txt")
);

// 指定编码
InputStreamReader isr = new InputStreamReader(
    new FileInputStream("test.txt"),
    "UTF-8"  // 指定UTF-8编码
);

// 指定GBK编码
InputStreamReader isr = new InputStreamReader(
    new FileInputStream("gbk.txt"),
    "GBK"
);

配合缓冲流

Java
// 转换流+缓冲流读取
BufferedReader br = new BufferedReader(
    new InputStreamReader(
        new FileInputStream("test.txt"),
        "UTF-8"
    )
);
String line;
while ((line = br.readLine()) != null) {
    System.out.println(line);
}
br.close();

OutputStreamWriter

功能

将字节输出流转换为字符输出流(Writer)。

使用方式

Java
// 默认编码
OutputStreamWriter osw = new OutputStreamWriter(
    new FileOutputStream("test.txt")
);

// 指定编码写入
OutputStreamWriter osw = new OutputStreamWriter(
    new FileOutputStream("utf8.txt"),
    "UTF-8"
);
osw.write("Hello World");
osw.close();

配合缓冲流

Java
BufferedWriter bw = new BufferedWriter(
    new OutputStreamWriter(
        new FileOutputStream("test.txt"),
        "UTF-8"
    )
);
bw.write("内容");
bw.newLine();
bw.close();

FileReader与InputStreamReader的区别

对比项FileReaderInputStreamReader
编码使用系统默认编码可指定任意编码
灵活性不能指定编码可指定编码
底层继承InputStreamReader转换流基类
适用场景系统默认编码文件需指定编码的文件
Java
// FileReader不能指定编码
FileReader fr = new FileReader("utf8.txt");  // 使用默认编码,可能乱码

// InputStreamReader可以指定编码
InputStreamReader isr = new InputStreamReader(
    new FileInputStream("utf8.txt"),
    "UTF-8"
);  // 正确读取UTF-8文件

常见编码类型

编码名称说明
UTF-8国际通用编码,推荐使用
GBK中文编码,兼容GB2312
ISO-8859-1西欧编码
UTF-16Unicode编码

推荐:文本文件统一使用UTF-8编码,避免乱码。

解决乱码示例

读取GBK文件

Java
// FileReader读取GBK文件可能乱码
FileReader fr = new FileReader("gbk.txt");  // 使用UTF-8默认编码读取

// 正确方式:指定GBK编码
InputStreamReader isr = new InputStreamReader(
    new FileInputStream("gbk.txt"),
    "GBK"
);

获取文件编码

Java
// 使用第三方库检测编码(如juniversalchardet)
// 实际项目中建议明确编码而非猜测

要点总结

  • 转换流是字节流与字符流的桥梁
  • InputStreamReader:字节→字符,可指定编码
  • OutputStreamWriter:字节→字符,可指定编码
  • FileReader使用默认编码,不能指定
  • 需指定编码必须使用转换流
  • 常见编码:UTF-8、GBK、ISO-8859-1
  • 推荐文本文件统一使用UTF-8编码

📝 发现内容有误?点击此处直接编辑

← 上一篇 缓冲流
下一篇 → 输入输出流
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库