字节流之数据输入输出流

一 介绍
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 stub
		String 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
中国
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值