IO模拟键盘输入输出


IO模拟键盘输入输出

看了毕向东老师关于模拟键盘录入的视频。
试验了下用自定义InputStream类的对象模拟键盘录入,用自定义PrintStream类的对象模拟键盘输出。
并写了下后来的小练习:
通过键盘录入数据。当输入一行数据后,就将该行数据进行打印。如果录入的数据时over,那么停止录入。
cmd_1为自己用byte数组接收一行命令并判断是否是over。
cmd_2是毕老师讲解的用StringBuilder接收命令字符串。
全部代码如下:

import java.io.*;

class  ReadIn
{
	public static void main(String[] args) 
	{
		//cmd_1();
		cmd_2();
	}

	public static void cmd_2() //毕向东的做法。用StringBuilder存储每次输入的命令
	{
		InputStream in = null;
		PrintStream out = null;
		StringBuilder sb = new StringBuilder();
		try
		{
			int length = 0;
			int ch;
			in = System.in;
			out = System.out;
			while((ch = in.read()) != -1)
			{
				if(ch == '\r')
					continue;
				else if(ch == '\n')
				{
					String s = sb.toString();
					if("over".equals(s))
						break;
					out.println(s); //打印一行换行,用println而不用print,是因为sb中没存入'\n'
					sb.delete(0,sb.length());
				}
				else
					sb.append((char)ch);
			}
		}
		catch (IOException e)
		{
			System.out.println("读写失败!");
		}
		finally
		{
			if(in!=null)
			{
				try
				{
					in.close();
				}
				catch (IOException e)
				{
					System.out.println(e.toString());
				}
			}
		}
	}

	public static void cmd_1() //读取字节数组的做法
	{
		InputStream in = null; //自定义输入,模拟键盘录入。
		PrintStream out = null; //自定义输出,模拟键盘输出。
		try
		{
			int length;
			byte[] b = new byte[1024];
			String cmd;
			in = System.in;
			out = System.out;
			while((length=in.read(b))!= -1) //首先要获得敲入命令的长度
			{
				cmd = new String(b,0,length); //获取该命令。
				if((length == 6)&&("over".equals(cmd.substring(0,4)))) //如果命令长度为6(over加上'\r''\n'应6个字符)且前四个为over
					break; //String类的substring(begin,end)方法,是从begin位置(第一位是0)到(end-1)位置的子字符串!!
				else
					out.print(cmd); //用print打印一行换行,因为'\r'、'\n'都存入进了
			}
			out.close(); //PrintStream类的方法不抛出异常。
		}
		catch (IOException e)
		{
			System.out.println("读写失败!");
		}
		finally
		{
			if(in!=null)
			{
				try
				{
					in.close();
				}
				catch (IOException e)
				{
					System.out.println(e.toString());
				}
			}
		}
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哪知道

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值