DataInputStream 和 DataOutputStream 数据的字节输入流和字节输出流

1、数据流特性

1)属于处理流。因此 使用必须套接在字节流上。

2)专门用来处理八种数据类型和字符串。为此提供了专门的方法:

void writeByte(byte)             void readByte();

void writeInt(int)                   void readInt();

3)在处理八种基本数据类型时可以保证数据类型不改变

4)适合在网络中传输基本数据类型。

2、案例:将基本数据类型存盘到指定的路径中。从路径中读取基本数据类型  还有一部分异常处理。


代码:

public class DataInputOutputStream {

	public static void main(String[] args) {
		String path1 = "e:/hahha.txt";
		FileInputStream fis = null;
		FileOutputStream fos = null;
		DataInputStream dis = null;
		DataOutputStream dos = null;
		byte b1 = 123;
		int i1 = 3435;
		short s1 = 1234;
		String str = "张鑫铭";
		try {
			fos = new FileOutputStream(path1);
			fis = new FileInputStream(path1);
			dos = new DataOutputStream(fos);
			dos.writeByte(b1);
			dos.writeInt(i1);
			dos.writeShort(s1);
			dos.writeUTF(str);
			//刷新
			dos.flush();
			dis = new DataInputStream(fis);
			b1 = dis.readByte();
			s1 = dis.readShort();
			i1 = dis.readInt();
			str = dis.readUTF();
			System.out.println(b1);
			System.out.println(s1);
			System.out.println(i1);
			System.out.println(str);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 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();
				}
			}
			if( dis != null ){
				try {
					dis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		try {
			int re = add(Integer.MAX_VALUE,2);
			System.out.println("!!!!!!!:"+re);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("超出Integer最大数范围");
		}
	}
	
	public static int add(int a,int b) throws Exception{
		int c = a+b;
		if(c>Integer.MAX_VALUE||c<Integer.MAX_VALUE){
			
			throw new Exception();
		}
		else{
			
			return c;
		}
	}

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值