DataInputStream和DataOutputStream允许应用程序以与机器无关的方式从底层输入流中读取基本的java数据类型。也就是说,当读取一个数据时,不必关心这个数值是什么字节。
构造方法:
DataInputStream(InputStream in)
读取数据:
readBoolean()
readByte()
readChar()
readInt()
readFloat()
readDouble()
构造方法:
DataOutputStream(OutputStream out)
写入数据的方法:
writeBoolean(boolean v)
writeByte(int v)
writeChar(int v)
writeInt(int v)
writeFloat(float v)
writeDouble(double v)
这个Demo是一个使用DataOutputStream向文件中存取数据和使用DataInputStream从文件中读取数据的样例:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class DataInputStreamDataOutputStream {
public static void testDataInputStream(){
DataInputStream dis = null;
try {
File fin = new File("DataInputOutputStream.txt");
FileInputStream fis = new FileInputStream(fin);
dis = new DataInputStream(fis);
System.out.println(dis.readInt());
System.out.println(dis.readBoolean());
System.out.println(dis.readFloat());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(dis != null){
try {
dis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//测试DataOutputStream
public static void testDataOutputStream(){
DataOutputStream dos = null;
try {
File fout = new File("DataInputOutputStream.txt");
FileOutputStream fos = new FileOutputStream(fout);
dos = new DataOutputStream(fos);
dos.writeInt(1);
dos.writeBoolean(true);
dos.writeFloat((float) 1.203);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(dos != null){
try {
dos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
调用方式:
//测试DataOutputStream
DataInputStreamDataOutputStream.testDataOutputStream();
//测试DataInputStream
DataInputStreamDataOutputStream.testDataInputStream();
内容来源于网络,如有侵权,请联系作者删除!