1.对FileInputStream进行封装的操作,可以进行readInt,readDouble等 有些类似RandomAccessFile
2.DataOutputStream类提供三个写入字符串的方法:
writeBytes(String s) //JAVA的字符编码是Unicode的,第个字符占两个字节,writeBytes方法只是将每个字符的低字节写入,如果有中文会出现乱码
writeChars(String s) //writeChars是将字符的两个字节都写入
writeUTF(String str) //writeUTF将字符串按照UTF编码写入到目标设备(其中包括长度)
示例1:
DataInputStream dis = new DataInputStream(
new FileInputStream(file));int i = dis.readInt();
System.out.println(i);
i = dis.readInt();
System.out.println(i);
long l = dis.readLong();
System.out.println(l);
double d = dis.readDouble();
System.out.println(d);
String s = dis.readUTF();
System.out.println(s);
dis.close();//关闭上层流,下层流也会关闭的
DataOutputStream dos = new DataOutputStream(
new FileOutputStream(file));
dos.writeInt(10);
dos.writeInt(-10);
dos.writeLong(10l);
dos.writeDouble(10.5);
//采用utf-8编码写出
dos.writeUTF("中国");
//采用utf-16be编码写出 默认格式
dos.writeChars("中国");
dos.close();
示例2:
DataOutputStream dos=new DataOutputStream(new FileOutputStream("data.txt"));
FileInputStream bis=new FileInputStream("data.txt");
DataInputStream dis=new DataInputStream(bis);
String str="你好hi";
dos.writeUTF(str); //按UTF-8格式写入
dos.writeChars(str); //按字符写入
//按字节写入有两种方法,第一种方法只能适应无汉字的情况;
//方法1writeBytes在写入时会把所有的字符都按1个字节写入,而汉字的表示需要2个字节,就造成了数据的丢失,读入时就出现乱码。
//方法2在将字符串转换为字节数组时就把汉字字符变为了2个字节,这样读取的时候就不会出现问题
dos.writeBytes(str);//方法1:将整个字符串按字节写入
byte[] b=str.getBytes(); //方法2:将字符串转换为字节数组后再逐一写入
dos.write(b);
dos.close();
///////////////////////////////////////读取//////////////////////////////////////////////////////////////
//按UTF-8格式读取
System.out.println(dis.readUTF());
//字符读取
char [] c=new char[4];
for(int i=0;i<4;i++){
c[i]=dis.readChar(); //读取4个字符
}
System.out.print(new String(c,0,4));
System.out.println();
//字节读取
byte [] b1=new byte[4];
dis.read(b1); //读取4个字节
System.out.print(new String(b1,0,4));//输出时会出现乱码
System.out.println();
//字节读取,此时长度我们未知,所以设定的比较大
byte [] b2=new byte[1024];
int len=dis.read(b2);
System.out.println(new String(b2,0,len));
}