java 中 datainputstream 通过包装一个底层字节输入流,提供读取基本类型(如 int, double, boolean)的方法。要使用它,只需将 fileinputstream 等字节流作为参数传入其构造函数,然后调用对应的 readxxx() 方法即可按写入时的顺序还原数据。

DataInputStream 读取 int 和 double 的具体步骤是什么
读取 int 和 double 时,分别调用 readInt() 和 readDouble() 方法。这些方法会从底层流中读取固定数量的字节(int 为 4 字节,double 为 8 字节),并将其转换为对应的基本类型值。如果读取时底层流中的数据不足或格式不匹配,会抛出 EOFException 或 IOException。

import java.io.*;
public class DataInputDemo {
public static void main(String[] args) throws IOException {
// 模拟写入的数据:一个 int 和一个 double
int i = 100;
double d = 3.14;
// 创建临时文件用于演示
File tempFile = new File("temp.dat");
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(tempFile))) {
dos.writeInt(i);
dos.writeDouble(d);
}
// 使用 DataInputStream 读取
try (DataInputStream dis = new DataInputStream(new FileInputStream(tempFile))) {
int readInt = dis.readInt();
double readDouble = dis.readDouble();
System.out.println("Read Int: " + readInt);
System.out.println("Read Double: " + readDouble);
}
}
}
运行上述代码,预期输出为:Read Int: 100Read Double: 3.14
注意:读取的顺序必须与写入的顺序完全一致。如果先写 double 后写 int,但读取时先调用 readInt(),则会导致数据解析错误。
DataInputStream 读取 boolean 和 byte 的行为有何不同
读取 boolean 时,readBoolean() 方法只读取 1 个字节,如果该字节非零则返回 true,否则返回 false。而 readByte() 方法读取 1 个字节并直接将其转换为 byte 类型(有符号,范围 -128 到 127)。两者虽然都只读 1 个字节,但解释方式不同:readBoolean 是逻辑判断,readByte 是数值转换。

import java.io.*;
public class DataInputBoolByteDemo {
public static void main(String[] args) throws IOException {
File tempFile = new File("temp2.dat");
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(tempFile))) {
dos.writeBoolean(true); // 写入 1 个字节 0x01
dos.writeByte(100); // 写入 1 个字节 0x64
}
try (DataInputStream dis = new DataInputStream(new FileInputStream(tempFile))) {
boolean b = dis.readBoolean();
byte by = dis.readByte();
System.out.println("Read Boolean: " + b);
System.out.println("Read Byte: " + by);
}
}
}
运行上述代码,预期输出为:Read Boolean: trueRead Byte: 100
当 DataInputStream 遇到空输入时会返回什么
当 DataInputStream 尝试从空输入流中读取任何基本类型时,会立即抛出 java.io.EOFException。这是因为所有 readXxx() 方法在内部都会检查是否有足够的数据可读,如果没有,就会抛出此异常以指示数据流已结束。例如,对一个空的 ByteArrayInputStream 调用 dis.readInt(),将直接触发 EOFException,而不是返回默认值或 null。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











