数据流概述
数据流也是处理流的一种,为了方便操作Java语言中的基本数据类型和String类型的数据,可以使用数据流来进行操作。数据流可以将我们Java语言中的基本数据类型和String类型的数据持久化存储到硬盘中,需要的时候就可以使用数据输入流将硬盘中持久存储的数据读入到程序中。这里的持久化存储和我们单独对文本的存储是不一样的,持久化存储到硬盘中的文件不是直接打开看的(打开看有的很多都会出现乱码),只是为了进行存储。
数据流分类
- DataOutputStream:数据输出流,一般是套接在OutputStream类的子类对象上
- DataInputStream:数据输入流,一般是套接在InputStream类的子类对象上
DataOutputStream
构造方法
public DataOutputStream(OutputStream out):创建一个新的数据输出流对象
FileOutputStream fos=new FileOutputStream("D:\\aaa\\helloworld.txt");
DataOutputStream dos=new DataOutputStream(fos);
常用方法
- void writeBoolean()
dos.writeBoolean(true);
- void writeByte()
byte b='?';
dos.writeByte(b);
- void writeShort()
short s=12;
dos.writeShort(s);
- void writeInt()
int i=3;
dos.writeInt(i);
- void writeChar()
char c='a';
dos.writeChar(c);
- void writeFloat()
float f=9;
dos.writeFloat(f);
- void writeDouble()
double d=7.2;
dos.writeDouble(d);
- void writeLong()
long l=10;
dos.writeLong(l);
- void writeUTF():写字符串
- void writeBytes(String s)
String str="中国";
dos.writeUTF(str);
dos.writeBytes(str);
DataInputStream
注意:我们使用数据输出流是按照什么顺序进行存储的,这个时候如果我们使用数据输入流读取时,也要按照相同的顺序读取
构造方法
public DataInputStream(InputStream in):创建一个新的数据输入流对象
FileInputStream fis=new FileInputStream("D:\\aaa\\helloworld.txt");
DataInputStream dis=new DataInputStream(fis);
常用方法
- boolean readBoolean()
//dos.writeBoolean(true);
boolean boo=dis.readBoolean();
System.out.println(boo);
//输出:true
- byte readByte()
/*
byte b='?';
dos.writeByte(b);
*/
byte by=dis.readByte();
System.out.println(by);
//输出:63
- short readShort()
/*
short s=12;
dos.writeShort(s);
*/
short sh=dis.readShort();
System.out.println(sh);
//输出:12
- int readInt()
/*
int i=3;
dos.writeInt(i);
*/
int in=dis.readInt();
System.out.println(in);
//输出:3
- char readChar()
/*
char c='a';
dos.writeChar(c);
*/
char ch=dis.readChar();
System.out.println(ch);
//输出:a
- float readFloat()
/*
float f=9;
dos.writeFloat(f);
*/
float fl=dis.readFloat();
System.out.println(fl);
//输出:9.0
- double readDouble()
/*
double d=7.2;
dos.writeDouble(d);
*/
double db=dis.readDouble();
System.out.println(db);
//输出:7.2
- long readLong()
/*
long l=10;
dos.writeLong(l);
*/
long lo=dis.readLong();
System.out.println(lo);
//输出:10
- String readUTF():读取字符串
/*
String str="中国";
dos.writeUTF(str);
*/
String ss=dis.readUTF();
System.out.println(ss);
//输出:中国