对于基本数据类型的输入输出流操作,java专门提供了一组类:DataInputStream和DataOutputstream
构造函数:
——1,DataInputStream(InputStream in)
——2,DataOutputStream(OutputStream out)
特有方法:
readInt()---writeInt(int a)
readDouble()---writeDouble(double a)
readBoolean()---writeBoolean(boolean a)
readUTF()---writeUTF(String str)//以与机器无关方式使用 UTF-8 修改版编码将一个字符串写入基础输出流
演示代码:
import java.io.*;
class DataStreamDemo
{
public static void main(String[] args) throws IOException
{
write();
read();
}
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void write() throws IOException
{
DataOutputStream dos=new DataOutputStream(new FileOutputStream("Data.txt"));
dos.writeInt(4);
dos.writeDouble(15.6);
dos.writeBoolean(true);
dos.writeUTF("呵呵");
dos.close();
}
public static void read() throws IOException
{
DataInputStream dis=new DataInputStream(new FileInputStream("Data.txt"));
//按顺序读取
sop(dis.readInt());
sop(dis.readDouble());
sop(dis.readBoolean());
sop(dis.readUTF());
dis.close();
}
}
/*
结果:
4
15.6
true
呵呵
*/
文件:
由于输入输出是字节流,到记事本中会查表转换成字符,所以呈现乱码属于正常现象