作用
简单来说,就是可以从二进制流中读取数据并转化为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 对象,就可以往其中写入内容.写成二进制文件,就相当于序列化了.