java 监听控制台输入

分享一下我写的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();
            }
        }

    }
}

 

 

转载于:https://www.cnblogs.com/memoryLost/p/11083131.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我了解您的要求。以下是一个简单的Java代码示例,用于监听USB扫描枪数据: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.TooManyListenersException; import javax.usb.UsbConfiguration; import javax.usb.UsbDevice; import javax.usb.UsbDeviceDescriptor; import javax.usb.UsbEndpoint; import javax.usb.UsbException; import javax.usb.UsbHostManager; import javax.usb.UsbHub; import javax.usb.UsbInterface; import javax.usb.UsbPipe; import jssc.SerialPort; import jssc.SerialPortEvent; import jssc.SerialPortEventListener; import jssc.SerialPortException; public class USBScannerListener implements SerialPortEventListener { private static final int VENDOR_ID = 0x067B; private static final int PRODUCT_ID = 0x2303; private static final int DATA_BITS = 8; private static final int STOP_BITS = 1; private static final int PARITY = 0; private static final int BAUD_RATE = 9600; private SerialPort serialPort; public USBScannerListener() { // 查找特定的 USB 设备 UsbDevice device = findDevice(VENDOR_ID, PRODUCT_ID); if (device == null) { System.err.println("USB Scanner not found."); return; } // 在USB设备上找到输入端点 UsbInterface iface = findInterface(device); UsbEndpoint endpoint = (UsbEndpoint) iface.getUsbEndpoints().get(0); try { // 打开 USB 传输管道 UsbPipe pipe = endpoint.getUsbPipe(); pipe.open(); // 设置串口参数 serialPort = new SerialPort("COM1"); serialPort.openPort(); serialPort.setParams(BAUD_RATE, DATA_BITS, STOP_BITS, PARITY); // 注册串口数据监听事件 serialPort.addEventListener(this); serialPort.setEventsMask(SerialPort.MASK_RXCHAR); } catch (UsbException | TooManyListenersException | SerialPortException ex) { System.err.println("Error initializing USB scanner listener: " + ex.getMessage()); } } private UsbDevice findDevice(int vendorId, int productId) { UsbDevice device = null; try { // 获取 USB 根集线器 UsbHub rootHub = UsbHostManager.getUsbServices().getRootUsbHub(); // 递归遍历 USB 树来查找设备 device = findDevice(rootHub, vendorId, productId); } catch (SecurityException | UsbException ex) { System.err.println("Error finding USB device: " + ex.getMessage()); } return device; } private UsbDevice findDevice(UsbHub hub, int vendorId, int productId) throws SecurityException, UsbException { UsbDevice device = null; // 遍历每个 USB 设备 for (UsbDevice d : (Iterable<UsbDevice>) hub.getAttachedUsbDevices()) { // 如果设备有子集线器,递归查找子集线器 if (d.isUsbHub()) { device = findDevice((UsbHub) d, vendorId, productId); if (device != null) { break; } } // 如果设备匹配给定的厂商ID和产品ID,则返回设备USB UsbDeviceDescriptor desc = d.getUsbDeviceDescriptor(); if (desc.idVendor() == vendorId && desc.idProduct() == productId) { device = d; break; } } return device; } private UsbInterface findInterface(UsbDevice device) throws UsbException { UsbInterface iface = null; // 遍历每个配置并找到第一个具有输入端点的接口 for (UsbConfiguration config : (Iterable<UsbConfiguration>) device.getUsbConfigurations()) { for (UsbInterface i : (Iterable<UsbInterface>) config.getUsbInterfaces()) { if (i.getUsbEndpoints().size() > 0) { iface = i; break; } } if (iface != null) { break; } } if (iface == null) { throw new UsbException("Device does not have any interfaces with input endpoints."); } return iface; } @Override public void serialEvent(SerialPortEvent event) { if (event.isRXCHAR()) { try { // 读取串口数据并输出到控制台 String data = serialPort.readString(); System.out.println(data); } catch (SerialPortException ex) { System.err.println("Error reading data from serial port: " + ex.getMessage()); } } } public static void main(String[] args) throws IOException { // 创建 USB 扫描仪侦听器 USBScannerListener listener = new USBScannerListener(); // 在按下回车键之前等待用户输入 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Press Enter to exit."); br.readLine(); // 关闭串口和 USB 管道 try { listener.serialPort.closePort(); listener.serialPort.removeEventListener(); listener.serialPort = null; } catch (SerialPortException ex) { System.err.println("Error closing serial port: " + ex.getMessage()); } } } ``` 这个代码在 jssc 库的帮助下工作,它是一组Java命令,可以访问串口和USB设备和数据的通信。 若要使用此示例,请确保已安装jssc库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值