DataInputStream 是用于按字节顺序读取已编码Java基本类型的类,需包装底层InputStream;必须按DataOutputStream写入顺序严格读取,否则类型错位,且易抛EOFException。

DataInputStream 是 Java 中用于从输入流中按字节顺序读取已编码的原始 Java 数据类型(如 int、double、boolean 等)的类。它必须包装一个底层的 InputStream(比如 FileInputStream 或 ByteArrayInputStream),不能直接创建实例。
1. 创建 DataInputStream 实例
必须传入一个已打开的字节输入流:
- 从文件读取:
new DataInputStream(new FileInputStream("data.bin")) - 从字节数组读取:
new DataInputStream(new ByteArrayInputStream(bytes)) - 注意:推荐配合
try-with-resources自动关闭资源
2. 按写入顺序读取基本类型
DataInputStream 的读取方法严格依赖数据写入时的格式和顺序。常见方法包括:
-
readInt():读取 4 字节,按大端序(network byte order)转为int -
readDouble():读取 8 字节,转为double -
readBoolean():读取 1 字节,0 为false,非 0 为true -
readUTF():读取 UTF-8 编码的字符串(注意:不是readLine(),后者已过时且不推荐) -
readByte()、readShort()、readLong()、readFloat()等一一对应
3. 注意事项与常见问题
使用不当容易抛出异常或读错数据:
- 如果流末尾不足所需字节数(如只剩 2 字节却调用
readInt()),会抛EOFException - 读取顺序必须和
DataOutputStream写入顺序完全一致,否则类型错位(比如把int当作double读) -
readUTF()只能读DataOutputStream.writeUTF()写入的内容,不能读普通文本文件中的中文 - 不支持字符编码切换,所有文本操作都基于修改版 UTF-8(带长度前缀)
4. 完整示例:写入再读取
先用 DataOutputStream 写入,再用 DataInputStream 读回:
<font color="#888">// 写入
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("test.dat"))) {
dos.writeInt(123);
dos.writeDouble(3.14159);
dos.writeBoolean(true);
dos.writeUTF("Hello世界");
}</font>
<font color="#888">// 读取
try (DataInputStream dis = new DataInputStream(new FileInputStream("test.dat"))) {
int i = dis.readInt(); // 123
double d = dis.readDouble(); // 3.14159
boolean b = dis.readBoolean(); // true
String s = dis.readUTF(); // "Hello世界"
}</font>
不复杂但容易忽略细节,关键是匹配写入/读取逻辑和异常处理。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











