Java IO之DataInputStream

来源:互联网 发布:php搭建好显示http500 编辑:程序博客网 时间:2024/06/08 09:27

FileInputStream和FileOutStream在读写文件时不考虑数据的类型,FileWriter和FileReader在读写文件时,将所有的数据都看做字符,但是有时候我们需要将各种类型的数据写入文件或是从文件中读取,DataInputStream类和DataOutStream类可以满足需求。

DataInputStream类可以输入任何类型的数据,但它不可以单独使用,需要配合其他字节输入流一起使用,DataInputStream类的构造方法只有一种方式:

DataInputStream(InputStream in)

说明:利用其他的字节输入流创建数据输入流对象


如:将文件输入流包装成数据输入流,以便从文件中读取各种类型的数据

FileInputStream fis = new FileInputStream("data.dat");DataInputStream dis = new DataInputStream(fis);

DataInputStream类的常用方法

//从数据输入流中读取一个boolean型数据final boolean readBoolean() throws IOException//从数据输入流中读取一个char类型数据final char readChar() throws IOException//从数据输入流中读取一个int类型数据final int readInt() throws IOException//从数据输入流读取一个Long类型的数据final long readLong() throws IOException//从数据输入流中读取一个Float类型的数据final float readFloat() throws IOException//从数据输入流中读取一个Double类型的数据final double readDouble() throws IOException


DataOutputStream类

DataOutputStream类可以输出任何类型的数据,同样也需要配合其他字节输出流一起使用。

DataOutputStream类的构造方法如下:

DataOutputStream(OutputStream out)
说明:利用其它的字节流创建数据输出流对象

如:将文件输出流包装成数据输出流,以便往文件中写入各种类型的数据

FileOutputStream fos = new FileOutputStream("data.dat");DataOutputStream dos = new DataOutputStream(fos);
DataOutputStream类的常用方法

//往数据输出流中写入一个boolean类型的数据final void writeBoolean(boolean v) throws IOException//往数据输出流中写入一个char类型的数据final void writeChar(char v) throws IOException//往数据输出流中写入一个int类型的数据final void writeInt(int v) throws IOException//往数据输出流中写入一个long类型的数据final void writeLong(long v) throws IOException//往数据输出流中写入一个float类型的数据final void writeFloat(float v) throws IOException//往数据输出流中写入一个Double类型的数据final void writeDouble(double v) throws IOException





0 0
原创粉丝点击