JAVA-----IO篇五(数据流DataInputStream以及DataOutputStream)
DataInputStream和DataOutputStream属于数据流,在写数据时,能够将数据连同数据的类型一并写入文件。
DataOutputStream写的文件,只能够通过DataInputStream读取,并且写、读顺序要一致!不一致时会出现随机数,可以当做加密方式的一种。
DataOutputStream
public class DataOutputStreamTest {
public static void main(String[] args) throws Exception {
// 构造方法需要传入,OutputStream。而FileOutputStream属于OutputStream的子类
DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream("data"));
// 写数据
byte b=100;
short s=200;
int i = 300;
long l = 400L;
float f = 3.0F;
double d = 3.14;
boolean sex = false;
char c = 'c';
dataOutputStream.writeByte(b); //把数据以及数据的类型,一并写入到文件中
dataOutputStream.writeShort(s);
dataOutputStream.writeInt(i);
dataOutputStream.writeLong(l);
dataOutputStream.writeFloat(f);
dataOutputStream.writeDouble(d);
dataOutputStream.writeBoolean(sex);
dataOutputStream.writeChar(c);
// 刷新,关闭
dataOutputStream.flush();
dataOutputStream.close();
}
}
DataInputStream
/**
* @author cz
* @date 2020/6/18/018
* 读取使用DataOutputStream存储的文件时,只能使用DataInputStream,且需要读、写顺序必须一致
**/
public class DataInputStream Test {
public static void main(String[] args) throws Exception {
DataInputStream dataInputStream = new DataInputStream(new FileInputStream("data"));
//读文件是时,必须按照存放数据的顺序进行读取,可以理解为一种加密规则
byte b = dataInputStream.readByte();
short i = dataInputStream.readShort();
int i1 = dataInputStream.readInt();
long l = dataInputStream.readLong();
float v = dataInputStream.readFloat();
double v1 = dataInputStream.readDouble();
boolean b1 = dataInputStream.readBoolean();
char c = dataInputStream.readChar();
System.out.println(b); //100
System.out.println(i); //200
System.out.println(i1); //300
System.out.println(l); //400
System.out.println(v); //3.0
System.out.println(v1); //3.14
System.out.println(b1); //false
System.out.println(c); //c
//关闭流
dataInputStream.close();
}
}
这种流用的不是特别多,重在了解。