在 Java 中,InputStream 是 java.io 包中的一个抽象类,代表字节输入流,用于从源(如文件、网络连接、内存缓冲区等)读取原始字节数据(8位)。它是所有字节输入流的父类,常见子类包括:
FileInputStream:从文件读取字节ByteArrayInputStream:从字节数组读取BufferedInputStream:为其他输入流添加缓冲功能,提升读取性能ObjectInputStream:支持反序列化对象(需配合Serializable)System.in:标准输入流(类型为InputStream,通常被包装为Scanner或BufferedReader使用)
⚠️ 注意:InputStream 处理的是字节(byte),不直接处理字符(char)或文本编码;若需读取文本(如 UTF-8 字符串),应配合 InputStreamReader(桥接字节流与字符流)和 BufferedReader 使用。
示例:读取文件前10个字节
try (InputStream is = new FileInputStream("data.bin")) {
int b;
int count = 0;
while ((b = is.read()) != -1 && count < 10) {
System.out.printf("0x%02X ", b); // 以十六进制打印
count++;
}
} catch (IOException e) {
e.printStackTrace();
}
InputStream 和 Reader(如 InputStreamReader)的核心区别在于数据抽象层级与处理单位不同:
| 维度 | InputStream | Reader(字符流) |
|---|---|---|
| 数据单位 | 字节(byte,8位) | 字符(char,16位 Unicode 码元) |
| 用途定位 | 通用二进制数据读取(图片、音频、序列化对象、任意字节流) | 文本数据读取(字符串、源代码、配置文件等人类可读内容) |
| 编码处理 | ❌ 不涉及字符编码;原样读取字节,不理解“文本”含义 | ✅ 显式依赖字符编码(如 UTF-8、GBK),通过 InputStreamReader 将字节按指定编码解码为字符 |
| 继承体系 | 属于 java.io 中的字节流体系(InputStream → FilterInputStream → …) | 属于字符流体系(Reader → InputStreamReader → BufferedReader → …) |
| 典型使用场景 | 读取 .jpg, .class, ObjectInputStream, 网络原始报文 | 读取 .txt, .json, .xml, 日志文件等需按文本语义解析的内容 |
📌 关键桥梁:InputStreamReader 是字节流到字符流的桥接器——它以 InputStream 为源,按指定 Charset(如 StandardCharsets.UTF_8)将字节解码为字符,从而让 Reader 体系能安全处理文本。
✅ 正确用法示例(避免乱码):
// ✅ 推荐:显式指定编码,防止平台默认编码导致问题
try (InputStream is = new FileInputStream("hello.txt");
Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(reader)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
❌ 错误示范(隐式使用平台默认编码,高风险):
new InputStreamReader(new FileInputStream("hello.txt")); // ⚠️ 危险!编码不可控

2048

被折叠的 条评论
为什么被折叠?



