数据流
DataInputStream与DataOutputStream
-
DataOutputStream : 数据专属流
-
这个流可以将数据连同数据的类型一并写入文件
注意!:这个文件不是普通文本文件(这个文件使用记事本打不开)
-
-
DataInputStream : 数据字节输入流
- DataOutputStream写的文件,只能使用DataInputStream去读,并且读的时候需要提前写入的顺序
- 读的顺序需要和写入的顺序一致,才能正常取出数据
代码示例
public class DataOutputStreamTest {
public static void main(String[] args) {
DataOutputStream bos = null ;
DataInputStream in = null ;
try {
bos = new DataOutputStream(new FileOutputStream("data"));
in = new DataInputStream(new FileInputStream("data"));
//写数据
byte a = 100 ;
short b = 200 ;
int c = 300 ;
long d = 400L ;
float e = 3.0F ;
double f =3.14 ;
boolean g = false ;
char h = 'a' ;
//写
bos.writeByte(a);
bos.writeShort(b);
bos.writeInt(c);
bos.writeLong(d);
bos.writeFloat(e);
bos.writeDouble(f);
bos.writeBoolean(g);
bos.writeChar(h);
//开始读
byte q =in.readByte();
short w = in.readShort();
int r = in.readInt();
long t = in.readLong();
float y = in.readFloat();
double u = in.readDouble();
boolean i = in.readBoolean();
char o = in.readChar();
System.out.println(q);
System.out.println(w);
System.out.println(r+1000);
System.out.println(t);
System.out.println(y);
System.out.println(u);
System.out.println(i);
System.out.println(o);
bos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bos!=null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in!=null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
运行结果:
100
200
1300
400
3.0
3.14
false
a