DataInputStream 是数据输入流。它继承于FilterInputStream。
DataInputStream 是用来装饰其它输入流,它“允许应用程序以与机器无关方式从底层输入流中读取基本 Java 数据类型”。应用程序可以使用DataOutputStream(数据输出流)写入由DataInputStream(数据输入流)读取的数据。
结构:
java.lang.Object
java.io.InputStream
java.io.FilterInputStream
java.io.DataInputStream
构造器:
DataInputStream(InputStream in)
创建使用指定的底层InputStream的DataInputStream。
DataInputStream(InputStream in)
final int read(byte[] buffer, int offset, int length)
final int read(byte[] buffer)
final boolean readBoolean()
final byte readByte()
final char readChar()
final double readDouble()
final float readFloat()
final void readFully(byte[] dst)
final void readFully(byte[] dst, int offset, int byteCount)
final int readInt()
final String readLine()
final long readLong()
final short readShort()
final static String readUTF(DataInput in)
final String readUTF()
final int readUnsignedByte()
final int readUnsignedShort()
final int skipBytes(int count)
几个方法说明:
read: 父类的方法,读取一个字节:
public int read() throws IOException {
return in.read();
}
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));
}
public final short readShort() throws IOException {
int ch1 = in.read();
int ch2 = in.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (short)((ch1 << 8) + (ch2 << 0));
}
这里看到int占四个字节,short两字节,并且按高低位排列,互不干扰。
我们知道 int 是4个字节,所以他读了4次,他这样的封装为我们带来了极大的便利。
本文深入解析DataInputStream类,探讨其作为装饰器模式的应用,用于以机器无关的方式读取基本Java数据类型。文章详细介绍了DataInputStream的构造器、方法,如readInt、readShort等,以及它们如何简化数据读取过程。
3402

被折叠的 条评论
为什么被折叠?



