分享一下我写的java监听控制台输入并可以给出响应的功能。

很多时候需要监听控制台的输入内容,相当于信号监听,根据输入的内容做出相应的动作,这里给出我的一个简单实现。

要注意的是:监听得到的消息中前后的空格和中间连续的多个空格会被忽略只保留一个空格,不区分大小写。

package com.idealisan.cores;

import java.util.HashMap;
import java.util.Scanner; public class ConsoleListener {
HashMap<String, Action> answers = new HashMap<String, ConsoleListener.Action>();
Scanner scanner;
Action defaultAction; /**
* Add an action for a message.
* @param message A string trimed. Ignore case. It has no inner space sequence of two spaces or more.
* Example:"close connection"
* @param action The method action.act() will be called when scanner get the message.
*/
public void addAction(String message, Action action) {
answers.put(message.toLowerCase(), action);
} /**
*
* @param scanner Usually new Scanner(System.in).
* Will not be closed after listening.
* @param defaultAction The defaultAction.act() method will be called if an action is not added for a message.
*/
public ConsoleListener(Scanner scanner, Action defaultAction) {
this.scanner = scanner;
this.defaultAction = defaultAction; if (scanner == null || defaultAction == null) {
throw new NullPointerException("null params for ConsoleListener");
}
} public void removeAction(String message, Action action) {
answers.remove(message, action);
} public Action replaceAction(String message, Action action) {
return answers.replace(message, action);
} public void listenInNewThread() {
Thread t = new Thread() {
public void run() {
listen();
}
};
t.start();
} /**
* Use listenInNewThread() instead.
* Listen to console input in current thread. It blocks the thread.
*/
public void listen() {
while (true) {
String line = scanner.nextLine();
String msg = line.replaceAll("[\\s]+", " ");
msg = msg.trim().toLowerCase();
Action action = answers.get(msg);
if (action == null) {
action = defaultAction;
} action.act(line); }
} public static interface Action {
public void act(String msg);
}
}

演示:

package com.idealisan.test;

import java.util.Scanner;

import com.idealisan.cores.ConsoleListener;

/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) {
ConsoleListener cs = new ConsoleListener(new Scanner(System.in), new ConsoleListener.Action() { public void act(String msg) {
System.out.println("Console: " + msg);
}
});
cs.addAction("stop", new ConsoleListener.Action() { public void act(String msg) {
System.out.println("Console: Bye");
System.exit(0);
}
});
cs.addAction("stop repeating", new ConsoleListener.Action() { public void act(String msg) {
System.out.println("Console: ...");
}
});
cs.listenInNewThread(); while (true) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
}

java 监听控制台输入的更多相关文章

  1. Android EditText的输入监听,输入字符的动态获取

    http://itindex.net/detail/38974-android-edittext-%E7%9B%91%E5%90%AC 有时候我们可能会用到时时的监听EditText输入字符的时时监听 ...

  2. 实时监听input输入内容的N种方法

    现在有一个需求,需要我们实时监听input输入框中的内容,从而带来更好的用户体验,而不是等我们全部输入完毕才告诉我们格式不对首先我们创建一个input输入框 <form name='loginF ...

  3. Java监听模式

    说明 生活中,监听无处不在.比如说,手机播放音乐功能,也是一种监听:你不点击播放按钮,手机就不放歌,当你点击时,手机就播放音乐.即触发某种行为,便执行相应的动作. 组成 Java监听模式右三个部分组成 ...

  4. java监听事件

    2014年2月23日 09:51:54 成功添加了打开官网的事件, 回头研究下,那个打开url的类 java的System.getProperty()方法可以获取的值 ################ ...

  5. 使用jQuery监听扫码枪输入并禁止手动输入的实现方法

    @(知识点总结)[jquery|扫码抢] 基于jQuery的扫码枪监听.如果只是想实现监听获取条码扫码信息,可以直接拿来使用,如果有更多的条码判断处理逻辑需要自己扩展. 一.功能需求 使用扫码枪扫描条 ...

  6. 微信小程序监听input输入并取值

    小程序的事件分为两种,冒泡和非冒泡事件,像<form/>的submit事件,<input/>的input事件,<scroll-view/>的scroll事件等非冒泡 ...

  7. 实时监听input输入的变化(兼容主流浏览器)【转】

    遇到如此需求,首先想到的是change事件,但用过change的都知道只有在input失去焦点时才会触发,并不能满足实时监测的需求,比如监测用户输入字符数. 在经过查阅一番资料后,欣慰的发现firef ...

  8. [转] 实时监听input输入的变化(兼容主流浏览器)

    遇到如此需求,首先想到的是change事件,但用过change的都知道只有在input失去焦点时才会触发,并不能满足实时监测的需求,比如监测用户输入字符数. 在经过查阅一番资料后,欣慰的发现firef ...

  9. java 监听文件或者文件夹变化的几种方式

    1.log4j的实现的文件内容变化监听 package com.jp.filemonitor; import org.apache.log4j.helpers.FileWatchdog; public ...

随机推荐

  1. poj 3177&&3352 求边双联通分量,先求桥,然后求分量( 临界表代码)

    /*这道题是没有重边的,求加几条边构成双联通,求边联通分量,先求出桥然后缩点,成一个棵树 找叶子节点的个数*/ #include<stdio.h>//用容器写在3177这个题上会超内存,但 ...

  2. ZooKeeper搭建系列集 (这套很全,也很详细)

    原文链接:http://blog.csdn.net/shatelang/article/details/7596007 本篇文章结构: 总共包括10个系列 ZooKeeper系列之一:ZooKeepe ...

  3. CSTC 选课

    选课 [问题描述] 在大学里每个学生,为了达到一定的学分,必须从很多课程里选择一些课程来学习,在课程里有些课程必须在某些课程之前学习,如高等数学总是在其它课程之前学习.现在有N门功课,每门课有个学分, ...

  4. uva 10479(找规律+递归)

    题意:有一个初始序列第一个数字是0. 规律是把前一次推出来的每个数字x.先接x个0,然后接x+1. 0 –> 1 –> 02 –> 1003 –> 02110004 那么这个序 ...

  5. QQ好友列表数据模型封装

    QQ好友中的信息较多.假设我们单独从plist 中直接取出数据 是能够解决这个问题 可是相当复杂.以为列表中分组 .每组中还有不同信息 大致模型是 数组套数组  数组套字典 所以我们要封装数据模型 / ...

  6. QUERY_REWRITE_INTEGRITY

    QUERY_REWRITE_INTEGRITY Property Description Parameter type String Syntax QUERY_REWRITE_INTEGRITY = ...

  7. UVA - 10029 Edit Step Ladders (二分+hash)

    Description Problem C: Edit Step Ladders An edit step is a transformation from one word x to another ...

  8. ViewPage+Frament+listView滑动效果

    近期在做一个须要使用Frament+ViewPage制作一个滑动的效果,看了非常多资料,最终实现了,这与大家分享一下战果 总结一下.这里我做了一个Demo分享给大家 我的文件文件夹结构图 1.首先要有 ...

  9. linux命令之man和info

    linux命令之man和info man ➜ ~ man ls result: LS(1)中1这样的数字的意义例如以下所看到的: 代号 内容 1 用户在shell环境中能够操作的命令或可运行文件 2 ...

  10. 改你MB需求!

    改你MB需求! 原创 2015-12-08 尖峰视界 尖峰视界 我敏锐的觉察到,产品经理的头像開始闪动了.在0.1秒的时间内,我全身的血液都冲向了大脑.果然.右上角弹出了文件传输窗体. "最 ...