java DataInput接口

作用
简单来说,就是可以从二进制流中读取数据并转化为java的基本类型.

在这里插入图片描述
那么看看起方法.比如说
在这里插入图片描述

以readInt为例,看看源码

 /**
     * Reads four input bytes and returns an
     * {@code int} value. Let {@code a-d}
     * be the first through fourth bytes read. The value returned is:
     * <pre>{@code
     * (((a & 0xff) << 24) | ((b & 0xff) << 16) |
     *  ((c & 0xff) <<  8) | (d & 0xff))
     * }</pre>
     * This method is suitable
     * for reading bytes written by the {@code writeInt}
     * method of interface {@code DataOutput}.
     *
     * @return     the {@code int} value read.
     * @exception  EOFException  if this stream reaches the end before reading
     *               all the bytes.
     * @exception  IOException   if an I/O error occurs.
     */
    int readInt() throws IOException;

接口中当然没有方法体,具体干了什么要看起实现类.
以实现了datainput接口且比较常用的Datainputstream为例
在这里插入图片描述
readint这个就是读取四个字节的意思

 public final int readInt() throws IOException {
        int ch1 = in.read();
        int ch2 = in.read();
        int ch3 = in.read();
        int ch4 = in.read();
        if ((ch1 | ch2 | ch3 | ch4) < 0)
            throw new EOFException();
        return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
    }

调用了read方法,其作用为

从输入流中读取下一个数据字节。 以0到255的整数形式返回值字节。如果由于已到达流的末尾而没有字节可用,则返回值-1。
此方法将阻塞,直到可用输入数据,检测到流的末尾或引发异常为止。

举个应用

 @Override
  public void readFields(DataInput in) throws IOException {
    value = in.readLong();
  }

  @Override
  public void write(DataOutput out) throws IOException {
    out.writeLong(value);
  }

使用的时候,传入一个DataInput对象,就可以从中读取解析数据. 也可以说叫做反序列化.
传入一个DataOutput 对象,就可以往其中写入内容.写成二进制文件,就相当于序列化了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值