您的位置:首页 > 其它

IO模拟键盘输入输出

2012-03-14 02:02 323 查看
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());
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: