DataInputStream 与 DataOutputStream


	/*
	 * 文件内容是:
	 * 1234
	 * 4567
	 * 
	 * 读取后打印:
	 * 825373492
	 * 218772533
	 * 
	 * */
	@Test
	public void InDemo() throws IOException{
		DataInputStream in = new DataInputStream(new FileInputStream("E:/test/1.txt"));
		while(in.available()>0){
			int d  = in.readInt();
			System.out.println(d);
		}
		in.close();
	}
	

在TXT中输入1234 4567,使用DataInputStream 读取然后再控制台打印的是825.。。。

然后使用UE打开如下图


31是1的ASCII码,0D 0A是回车换行,都是些十六进制的数,将他们转换为十进制,正好是打印的内容。


2.

	@Test
	public void OutDemo() throws IOException{
		DataOutputStream out = new DataOutputStream(new FileOutputStream("E:/test/2.txt"));
		for (int i = 1; i <= 20; i++) {
			out.write(i);
		}
		out.close();
	}
这个也是一样的道理,将数字写出到文件,使用记事本打开看到一堆乱码,其实记事本是利用这些字符到编码表中找到对应的字符进行显示的。


3.

	@Test
	public void testEnd() {
		DataInputStream in = null;
		try {
			in = new DataInputStream(new FileInputStream("E:/test/1.txt"));
			while (true) {
				short read = in.readShort();
				System.out.println(read);
			}
		} catch (FileNotFoundException e) {
			System.err.println("文件找不到!");
			// e.printStackTrace();
		} catch (IOException e) {
			System.out.println("Over!");
			// e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
结束文件的读取除了测试1的available 之外,还可以使用捕获异常控制输入结束。

EOF就是end of file exception


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值