package com.dy.pipirrComCreator.console; import lombok.extern.slf4j.Slf4j; import java.io.Console; import java.io.PrintWriter; @Slf4j public class CommandConsole { private Console console ; private PrintWriter prtWrt ; private static final String myPassword = "123456" ; private static final String commandPrefix1 = ">>" ; private static final String commandPrefix2 = "$: " ; private static String commandPrefix = commandPrefix1 + commandPrefix2 ; public CommandConsole(Console console)throws Exception{ this.console = console ; if(this.console == null){ throw new Exception("严重错误,java控制台对象为空!"); } prtWrt = console.writer() ; } /** * 初始,检查并输出一些信息 * @throws Exception */ public void init() throws Exception{ PrintWriter prtWrt = console.writer() ; prtWrt.println("----------------------------------------"); prtWrt.println("-- --"); prtWrt.println("-- 欢迎使用命令生成器 --"); prtWrt.println("-- --"); prtWrt.println("----------------------------------------"); } /** * 执行控制台控制 * @return */ public boolean clientConsole(){ boolean exit = false ; try { this.login() ; exit = this.doConsole(); } catch (Exception e) { e.printStackTrace(); } return exit ; } private boolean login(){ while (true) { //String username = console.readLine(">>Username: "); char[] password = console.readPassword(">>Password: "); String passwordStr = String.valueOf(password) ; if (passwordStr.equals("help")) { console.printf("密码是%1$s.\n", myPassword); // 使用后应立即将数组清空,以减少其在内存中占用的时间,增强安全性 password = null; } else if(passwordStr.equals(myPassword)){ return true; } } } private boolean doConsole(){ boolean exit = false ; while (!exit) { String command = console.readLine(commandPrefix); try { exit = Command.dealCommand(command, prtWrt) ; }catch (Exception e){ e.printStackTrace(); } } return exit ; } public static void changeCommandPrefix(String prefix){ commandPrefix = commandPrefix1 + prefix ; } public static void recoverCommandPrefix(){ commandPrefix = commandPrefix1 + commandPrefix2 ; } }