字节流之数据输入输出流

来源:互联网 发布:增加淘宝店铺流量 编辑:程序博客网 时间:2024/05/21 08:57
一 介绍
DataOutputStream/DataInputStream对“流”功能的扩展,可以更加方便地读取int,long,字符等类型数据。
DataOutputStream
writeInt():写4个字节
writeDouble():写8个字节
writeUTF():写2+3*n个字节,其中前2个字节表示后面字节的长度

二 代码示例
package com.imooc.io;import java.io.DataOutputStream;import java.io.FileOutputStream;import java.io.IOException;public class DosDemo {public static void main(String[] args) throws IOException {String file = "demo/dos.dat";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();IOUtil.printHex(file);}}package com.imooc.io;import java.io.DataInputStream;import java.io.FileInputStream;import java.io.IOException;public class DisDemo {/** * @param args */public static void main(String[] args) throws IOException{// TODO Auto-generated method stubString file = "demo/dos.dat";IOUtil.printHex(file);   DataInputStream dis = new DataInputStream(   new FileInputStream(file));   System.out.println();   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();}}

三 运行结果
00 00 00 0a ff ff ff f6 00 00
00 00 00 00 00 0a 40 25 00 00
00 00 00 00 00 06 e4 b8 ad e5
9b bd 4e 2d 56 fd

00 00 00 0a ff ff ff f6 00 00
00 00 00 00 00 0a 40 25 00 00
00 00 00 00 00 06 e4 b8 ad e5
9b bd 4e 2d 56 fd
10
-10
10
10.5
中国
原创粉丝点击