提示

Java IO DataInputStream 使用示例。@ermo

回到上一级

# DataInputStream 使用示例

DataInputStream 也是一个装饰类实现,可以对 InputStream 进行增强。

主要构造器为:

public DataInputStream(InputStream in)

DataInputStream 同时实现了 DataInput 接口,内部定义了一些对基本类型数据的读方法:

boolean readBoolean() throws IOException;

int readInt() throws IOException;

long readLong() throws IOException;

double readDouble() throws IOException;

String readUTF() throws IOException;

来看一个简单的例子,order.txt 使用的是 DataOutputStream 示例 中写入的订单数据。

    public static List<Order> read() throws IOException {
        String filepath = "src/main/resources/order.txt";
        DataInputStream in = new DataInputStream(new FileInputStream(filepath));
        try {
            int size = in.readInt();
            List<Order> orders = new ArrayList<>(size);
            for (int i = 0; i < size; i++) {
                orders.add(new Order(in.readUTF(), in.readInt(), in.readDouble()));
            }
            return orders;
        } finally {
            in.close();
        }
    }

    public static void main(String[] args) throws IOException {
        List<Order> orders = read();
        for (Order order : orders) {
            System.out.println(order.toString());
        }
    }

上例中对 FileInputStream 进行了装饰,然后将 order.txt 中的订单数据读入内存中,转换为 Order 对象。

需要注意的是,在使用 DataInputStream 读数据时,读的顺序要和写入文件中的顺序完全一致,如果使用不同的顺序,将会抛出 java.io.EOFException 异常。