您的位置:

DataInputStream在Java中的使用

一、DataInputStream简介

DataInputStream是Java IO包中的一个类,用于读取二进制数据。它提供了一系列读取不同数据类型(如int、byte、char等)的方法。该类包含在与输入流相关的类中,因此常与FileInputStream等一起使用。

二、DataInputStream的构造函数

public DataInputStream(InputStream in)

该构造函数参数为输入流,在使用DataInputStream的时候需要先定义一个输入流。

三、DataInputStream的常用方法

1.read()

public final int read() throws IOException

该方法从输入流中读取下一个字节,并返回字节的值。如果已经到达流的末尾,则返回-1。

2.read(byte[] b, int off, int len)

public final int read(byte[] b,
         int off,
         int len)
          throws IOException

该方法从输入流中读取len个字节的数据,并将其存储在byte数组中,从off位置开始存储。返回读取到的字节数。

3.readBoolean()

public final boolean readBoolean() throws IOException

该方法从输入流中读取1个字节的数据,并返回一个布尔值。

4.readByte()

public final byte readByte() throws IOException

该方法从输入流中读取1个字节的数据,并返回一个byte类型的值。

5.readChar()

public final char readChar() throws IOException

该方法从输入流中读取2个字节的数据,并返回一个char类型的值。

6.readDouble()

public final double readDouble() throws IOException

该方法从输入流中读取8个字节的数据,并返回一个double类型的值。

7.readFloat()

public final float readFloat() throws IOException

该方法从输入流中读取4个字节的数据,并返回一个float类型的值。

8.readInt()

public final int readInt() throws IOException

该方法从输入流中读取4个字节的数据,并返回一个int类型的值。

9.readLong()

public final long readLong() throws IOException

该方法从输入流中读取8个字节的数据,并返回一个long类型的值。

10.readShort()

public final short readShort() throws IOException

该方法从输入流中读取2个字节的数据,并返回一个short类型的值。

11.readUTF()

public final String readUTF() throws IOException

该方法从输入流中读取一个UTF格式的字符串,并返回一个字符串值。

四、DataInputStream的使用示例

下面的代码演示了如何使用DataInputStream类读取一个二进制文件中的int、double、boolean、UTF格式的字符串。

import java.io.*;

public class DataInputStreamExample {

    public static void main(String[] args) {
        InputStream inputStream = null;
        DataInputStream dataInputStream = null;

        try {
            inputStream = new FileInputStream("test.dat");
            dataInputStream = new DataInputStream(inputStream);

            //读取int类型数据
            int intData = dataInputStream.readInt();
            System.out.println("读取int类型数据:" + intData);

            //读取double类型数据
            double doubleData = dataInputStream.readDouble();
            System.out.println("读取double类型数据:" + doubleData);

            //读取boolean类型数据
            boolean booleanData = dataInputStream.readBoolean();
            System.out.println("读取boolean类型数据:" + booleanData);

            //读取UTF格式字符串
            String strData = dataInputStream.readUTF();
            System.out.println("读取UTF格式字符串数据:" + strData);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                dataInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

五、总结

使用DataInputStream可以方便地读取二进制数据,并通过提供的各种方法读取不同数据类型的值。在使用DataInputStream的时候应特别注意读取数据的顺序,不要出现读取顺序和存储顺序不一致的情况,否则将导致读取到错误的数据。