为了方便的操作java语言中的基本数据类型和String类型的数据,可以使用数据流来进行操作
- 可以将我们java语言中的基本数据类型和String类型的数据持久化存储到硬盘中,需要的时候就可以使用数据输入流将硬盘中持久存储的数据读入到程序中
- 这里的持久化存储和我们单独对文本的存储是不一样的
- 我们持久化存储到硬盘中的文件不是直接打开看的,只是为了进行存储
- 打开看有的很多都会出现乱码 — 看不懂
- DateInputStream
- DateInputStream一般是套接在InputStream类子类的对象上
- InputStream就是四大抽象基类之一: 字节输入流
- DateInputStream一般是套接在InputStream类子类的对象上
- DateOutputStream
- DateOutputStream一般是套接在OutputStream类的子类的对象上
- OutputStream就是四大抽象基类之一: 字节输出流
- 注意: 我们使用数据输出流写出数据之后要进行显示的flush()方法进行清空缓冲区
- DateOutputStream一般是套接在OutputStream类的子类的对象上
- 数据流只有字节流,没有字符流
boolean readBoolean();
byte readByte();
short readShort();
int readInt();
char readChar();
float readFloat();
double readDouble();
long readLong();
String readUTF();
- 读取字符串
void readFully(byte[] b);
- 读取byte[]
void writeBoolean();
void writeByte();
void write Short();
void writeInt();
void writeChar();
void writeFloat();
void writeDouble();
void writeLong();
void writeUTF();
void writeBytes(String s);
这里我们通过两个程序来理解数据流的实际使用- 首先我们使用数据输出流将内存中的基本数据类型值,字符串写出到文件中
package IO流.数据流;
import java.io.FileOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class Demo1 {
public static void main(String[] args) throws IOException{
DataOutputStream dos = new DataOutputStream(new FileOutputStream("hihi.dat"));
dos.writeInt(13);
dos.writeBoolean(true);
dos.writeUTF("飞飞");
dos.flush();
dos.close();
}
}
- 其次这里我们使用数据输入流将硬盘中我们持久存储的文件进行读取,读取到内存中来
package IO流.数据流;
import java.io.FileInputStream;
import java.io.DataInputStream;
import java.io.IOException;
public class Demo2 {
public static void main(String[] args) throws IOException{
DataInputStream dis = new DataInputStream(new FileInputStream("hihi.dat"));
int i = dis.readInt();
System.out.println(i);
boolean b = dis.readBoolean();
System.out.println(b);
String s = dis.readUTF();
System.out.println(s);
dis.close();
}
}


![数据流 [Java] 数据流 [Java]](http://www.mshxw.com/aiimages/31/697560.png)
