DataInputStream和DataOutputStream是Java提供的数据输入、输出流。
两个类的构造方法如下:
public DataInputStream(InputStream in);
public DataOutputStream(OutputStream out)
从上面的构造方法我们可以看出,创建对象时,需要传入字节流对象,之所以这样是因为DataInputStream和DataOutputStream的实现使用的是装饰模式。
装饰模式:https://blog.csdn.net/b15735105314/article/details/115913647
上一篇我们讲解了FileInputStream和FileOutputStream,这两个流只能对单个字节或者字节数组进行读写操作,无法对其他的数据类型进行直接读写,这就导致我们在读写操作时需要添加数据转换成字节类型的步骤(或者字节类型转换成其他数据类型),然后才能进行读写操作,这种方式不太方便。
所以Java就在字节输入输出流的基础上封装了数据输入输出流DataInputStream和DataOutputStream。
数据输入流的方法如下(输出方法不介绍,反着来就行):
public final int read(byte b[]) throws IOException {}
public final int read(byte b[], int off, int len) throws IOException {}
public final void readFully(byte b[]) throws IOException {}
public final void readFully(byte b[], int off, int len) throws IOException {}
public final int skipBytes(int n) throws IOException {}
public final boolean readBoolean() throws IOException {}
public final byte readByte() throws IOException {}
public final int readUnsignedByte() throws IOException {}
public final short readShort() throws IOException {}
public final int readUnsignedShort() throws IOException {}
public final char readChar() throws IOException {}
public final int readInt() throws IOException {}
public final long readLong() throws IOException {}
public final float readFloat() throws IOException {}
public final double readDouble() throws IOException {}
public final String readUTF() throws IOException {}
上面所有的读方法除了两个方法名是read的方法之外,其他读方法都有EOFException,EOFException是在读取过程中到达文件末尾,抛出此异常。
例如readShort()方法如果读取的字节数不满2个字节的话,会抛出EOFException异常。再如一个文件只有5个字节,第一次使用readShort()读取(成功读取),第二次使用readInt()读取,那么读取的时候,流的指针所在位置到文件结尾就只有3个字节,所以使用readInt()的时候,会抛出EOFException异常。
示例:
public static void output() throws IOException {
FileOutputStream fos = new FileOutputStream("test03.txt");
DataOutputStream dataOutputStream = new DataOutputStream(fos);
dataOutputStream.write(5); //该方法输出参数的低8八位
dataOutputStream.writeChar('e');
dataOutputStream.writeFloat(2.12f);
dataOutputStream.writeInt(20);
dataOutputStream.writeByte(10);
fos.flush();
fos.close();
}
public static void input() throws IOException {
FileInputStream fis = new FileInputStream("test03.txt");
DataInputStream dataInputStream = new DataInputStream(fis);
int result01 = dataInputStream.read();
System.out.println(result01);
char result02 = dataInputStream.readChar();
System.out.println(result02);
float result03 = dataInputStream.readFloat();
System.out.println(result03);
float result04 = dataInputStream.readInt();
System.out.println(result04);
byte result05 = dataInputStream.readByte();
System.out.println(result05);
dataInputStream.close();
}
输出结果:
5
e
2.12
20.0
10