IO模拟键盘输入输出
2012-03-14 02:02
323 查看
IO模拟键盘输入输出
看了毕向东老师关于模拟键盘录入的视频。
试验了下用自定义InputStream类的对象模拟键盘录入,用自定义PrintStream类的对象模拟键盘输出。
并写了下后来的小练习:
通过键盘录入数据。当输入一行数据后,就将该行数据进行打印。如果录入的数据时over,那么停止录入。
cmd_1为自己用byte数组接收一行命令并判断是否是over。
cmd_2是毕老师讲解的用StringBuilder接收命令字符串。
全部代码如下:
看了毕向东老师关于模拟键盘录入的视频。
试验了下用自定义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()); } } } } }
相关文章推荐
- 直接IO模拟键盘源代码
- 模拟键盘输入器
- 利用键盘上的上下左右(回车)键模拟出tab 键的功能上下左右移动焦点
- VC C++ WinIo按键 键盘模拟
- Android查询:模拟键盘鼠标事件(adb shell 实现)
- MSP430FG439上实现IO模拟UART以及移植要点解析
- c#类模拟键盘和鼠标以及内存读取
- c#模拟键盘输入
- c++中的io输入输出
- 模拟键盘鼠标的API,写压力测试程序常用于模拟点击
- Linux 下模拟键盘输入
- IO(输入输出)-字节流
- delphi 模拟键盘
- C#模拟键盘事件
- IO输入输出之Reader、Writer
- vc模拟键盘输入的一些资料
- 黑马程序员0907_API部分+IO输入输出部分
- Java 模拟键盘输入的小Demo
- 输入输出处理(IO)(备忘)——上
- java简单实现双色球彩票模拟实例(数组、排序、方法、随机数、键盘输入)