天天看點

JAVA控制台輸入(Scanner)及輸出顔色

作者:MYJ2C混淆

這裡介紹如何控制java控制台輸入輸出内容的顔色。

1. 控制台輸入(Scanner)

java.util.Scanner 是 Java5 的新特征,我們可以通過 Scanner 類來擷取使用者的輸入。

public static void main(String[] args) {
        //建立一個掃描器對象,用于接收鍵盤資料
        Scanner scanner = new Scanner(System.in);
        //next方式接收字元串(不可以接收空格)
        System.out.println("Next方式接收:");
        //判斷使用者還有沒有輸入字元
        if (scanner.hasNext()) {
            String str = scanner.next();
            System.out.println("輸入内容:" + str);
        }
        // 凡是屬于IO流的類如果不關閉會一直占用資源.要養成好習慣用完就關掉.
        // 就好像你接水完了要關 水龍頭一樣.很多下載下傳軟體或者視訊軟體如果你不徹底關,
        // 都會自己上傳下載下傳進而占用資源,你就會覺得 卡,這一個道理.
        scanner.close();
    }
           
JAVA控制台輸入(Scanner)及輸出顔色

接下來我們使用另一個方法來接收資料:nextLine()

public static void main(String[] args) {
        //建立一個掃描器對象,用于接收鍵盤資料
        Scanner scanner = new Scanner(System.in);
        //nextLine方式接收字元串(可以接收空格)
        System.out.println("NextLine方式接收:");
        //判斷使用者還有沒有輸入字元
        if (scanner.hasNextLine()) {
            String str = scanner.nextLine();
            System.out.println("輸入内容:" + str);
        }
        // 凡是屬于IO流的類如果不關閉會一直占用資源.要養成好習慣用完就關掉.
        // 就好像你接水完了要關 水龍頭一樣.很多下載下傳軟體或者視訊軟體如果你不徹底關,
        // 都會自己上傳下載下傳進而占用資源,你就會覺得 卡,這一個道理.
        scanner.close();
    }           
JAVA控制台輸入(Scanner)及輸出顔色

next 和 nextLine的差別

next():

一定要讀取到有效字元後才可以結束輸入。

對輸入有效字元之前遇到的空白,next() 方法會自動将其去掉。

隻有輸入有效字元後才将其後面輸入的空白作為分隔符或者結束符。

next() 不能得到帶有空格的字元串。

nextLine():

以Enter為結束符,也就是說 nextLine()方法傳回的是輸入回車之前的所有字元。

可以獲得空白。

2、java控制台輸出顔色控制

在java語言中,可以通過\033特殊轉義字元實作輸出格式控制,如下是一個例子。

public class MYJ2CTestOutputControl {
    /**
     * 通過\033特殊轉義字元實作輸出格式控制     * @param content, 待格式化的内容
     * @param fontColor, 字型顔色:30黑 31紅 32綠 33黃 34藍 35紫 36深綠 37白
     * @param fontType, 字型格式:0重置 1加粗 2減弱 3斜體 4下劃線 5慢速閃爍 6快速閃爍
     * @param backgroundColor, 字背景顔色:40黑 41紅 42綠 43黃 44藍 45紫 46深綠 47白
     * */    
    public static String getFormatOutputString(String content, int fontColor, int fontType, int backgroundColor){
        return String.format("\033[%d;%d;%dm%s\033[0m", fontColor, fontType, backgroundColor, content);
    }
    /**
     * 通過\033特殊轉義字元實作輸出格式控制,獲得帶顔色的字型輸出     * @param content, 待格式化的内容
     * @param fontColor, 字型顔色:30黑 31紅 32綠 33黃 34藍 35紫 36深綠 37白
     * */    
    public static String getColoredOutputString(String content, int fontColor){
        return String.format("\033[%dm%s\033[0m", fontColor, content);
    }
    /**
     * 通過\033特殊轉義字元實作輸出格式控制,獲得帶背景顔色的字型輸出     * @param content, 待格式化的内容
     * @param backgroundColor, 字背景顔色:40黑 41紅 42綠 43黃 44藍 45紫 46深綠 47白
     * */    
    public static String getBackgroundColoredOutputString(String content, int backgroundColor){
        return String.format("\033[%dm%s\033[0m", backgroundColor, content);
    }

    /**
     * 能接受一個順序辨別,按順序産生帶顔色的輸出字元串     * */   
    public static String orderedColorString(String content, int i){
        int tmpColor = 31 + (i % 7);
        return String.format("\033[%dm%s\033[0m", tmpColor, content);
    }

    public static void main(String []args){
        System.out.println(getFormatOutputString("字型顔色為紅色,背景色為黃色,帶下劃線", 31, 4, 43));
        //按順序輸出各個顔色代碼的字元串
        for(int i = 0; i < 7; i++){
            System.out.println(getColoredOutputString(String.format("color code: %d", 31 + i), 31 + i));
        }
        //按順序輸出各個背景顔色代碼的字元串
        for(int i = 0; i < 7; i++){
            System.out.println(getBackgroundColoredOutputString(String.format("background color code: %d", 41 + i), 41 + i));
        }
        //按順序輸出各個顔色代碼的字元串
        for(int i = 0; i < 7; i++){
            System.out.println(orderedColorString(String.format("font color code: %d", 31 + i), i));
        }
    }
}
           

運作前面的程式,可以看到如下輸出。

JAVA控制台輸入(Scanner)及輸出顔色

3、通過顔色區分不同編碼格式輸出

這裡是一個例子,主要是展示java字元串不同編碼格式的輸出。

/**
 * Created by chengxia on 2022/8/19. */
public class MYJ2CTestOutputControl {
    /**
     * 通過\033特殊轉義字元實作輸出格式控制     * @param content, 待格式化的内容
     * @param fontColor, 字型顔色:30黑 31紅 32綠 33黃 34藍 35紫 36深綠 37白
     * @param fontType, 字型格式:0重置 1加粗 2減弱 3斜體 4下劃線 5慢速閃爍 6快速閃爍
     * @param backgroundColor, 字背景顔色:40黑 41紅 42綠 43黃 44藍 45紫 46深綠 47白
     * */
    public static String getFormatOutputString(String content, int fontColor, int fontType, int backgroundColor){
        return String.format("\033[%d;%d;%dm%s\033[0m", fontColor, fontType, backgroundColor, content);
    }
    /**
     * 通過\033特殊轉義字元實作輸出格式控制,獲得帶顔色的字型輸出     * @param content, 待格式化的内容
     * @param fontColor, 字型顔色:30黑 31紅 32綠 33黃 34藍 35紫 36深綠 37白
     * */
    public static String getColoredOutputString(String content, int fontColor){
        return String.format("\033[%dm%s\033[0m", fontColor, content);
    }
    /**
     * 通過\033特殊轉義字元實作輸出格式控制,獲得帶背景顔色的字型輸出     * @param content, 待格式化的内容
     * @param backgroundColor, 字背景顔色:40黑 41紅 42綠 43黃 44藍 45紫 46深綠 47白
     * */
    public static String getBackgroundColoredOutputString(String content, int backgroundColor){
        return String.format("\033[%dm%s\033[0m", backgroundColor, content);
    }

    /**
     * 能接受一個順序辨別,按順序産生帶顔色的輸出字元串     * */
    public static String orderedColorString(String content, int i){
        int tmpColor = 31 + (i % 7);
        return String.format("\033[%dm%s\033[0m", tmpColor, content);
    }

        /**
         * 将字元串str用字元c左補齊到長度len     * */
        private static String lpadString(String str, int len, char c){
            StringBuffer sb = new StringBuffer(str);
            for(int i = str.length(); i < len; i++){
                sb.insert(0, c);
            }
            return sb.toString();
        }
        /**
         * 将字元串轉換為CodeUnit(各個CodeUnit之間帶顔色區分)     * */
        public static String getColoredCodeUnitOfString(String str){
            StringBuffer sb = new StringBuffer();
            for(int i = 0; i < str.length(); i++){
                int tmpCodeUnit = (int)str.charAt(i);
                sb.append(orderedColorString(lpadString(Integer.toHexString(tmpCodeUnit), 4, '0').toUpperCase(), i));
            }
            return sb.toString();
        }
        /**
         * 将字元串轉換為CodePoint(各個CodePoint之間帶顔色區分)     * */
        public static String getColoredCodePointOfString(String str){
            StringBuffer sb = new StringBuffer();
            for(int i = 0; i < str.length(); i++){
                int tmpCodePoint = (int)str.codePointAt(i);
                sb.append(orderedColorString(lpadString(Integer.toHexString(tmpCodePoint), 4, '0').toUpperCase(), i));
                //如果目前這個CodePoint是增補字元集的話,兩個char表示一個CodePoint需要額外自增1處理
                if(Character.isSupplementaryCodePoint(tmpCodePoint)){
                    i++;
                }
            }
            return sb.toString();
        }
        /**
         * 将字元串轉換為不同編碼格式表示(各個字元的編碼之間帶顔色區分)     * */
        public static String getColoredHexEncodeOfString(String str, String encoding){
            StringBuffer sb = new StringBuffer();
            for(int i = 0; i < str.length(); i++){
                int tmpCodePoint = (int)str.codePointAt(i);
                String tmpSubStr = str.substring(i, i + 1);
                //如果目前這個CodePoint是增補字元集的話,兩個char表示一個CodePoint
                if(Character.isSupplementaryCodePoint(tmpCodePoint)){
                    tmpSubStr = tmpSubStr + str.substring(i + 1, i + 2);
                    i++;
                }
                try{
                    StringBuffer tmpSb = new StringBuffer();
                    byte[] tmpBytes = tmpSubStr.getBytes(encoding);
                    for(int iTmp = 0; iTmp < tmpBytes.length; iTmp++){
                        tmpSb.append(String.format("%02X", tmpBytes[iTmp]));
                    }
                    sb.append(orderedColorString(tmpSb.toString(), i));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            return sb.toString();
        }

        public static void main(String []args){
            String strDiffEncoding = "MYJ2C是一款Java混淆工具";
            //将字元串用各種編碼格式輸出
            System.out.println("?" + " encode in GB2312 output:    " + getColoredHexEncodeOfString("?", "GB2312"));
            System.out.println("?" + " encode in GBK output:    " + getColoredHexEncodeOfString("?", "GBK"));
            System.out.println("?" + " encode in GB18030 output:    " + getColoredHexEncodeOfString("?", "GB18030"));
            System.out.println(strDiffEncoding + " code unit output:           " + getColoredCodeUnitOfString(strDiffEncoding));
            System.out.println(strDiffEncoding + " code point output:          " + getColoredCodePointOfString(strDiffEncoding));
            System.out.println(strDiffEncoding + " encode in GB2312 output:    " + getColoredHexEncodeOfString(strDiffEncoding, "GB2312"));
            System.out.println(strDiffEncoding + " encode in BIG5 output:      " + getColoredHexEncodeOfString(strDiffEncoding, "BIG5"));
            System.out.println(strDiffEncoding + " encode in GBK output:       " + getColoredHexEncodeOfString(strDiffEncoding, "GBK"));
            System.out.println(strDiffEncoding + " encode in GB18030 output:   " + getColoredHexEncodeOfString(strDiffEncoding, "GB18030"));
            System.out.println(strDiffEncoding + " encode in UTF-8 output:     " + getColoredHexEncodeOfString(strDiffEncoding, "UTF-8"));
            System.out.println(strDiffEncoding + " encode in UTF-16 output:    " + getColoredHexEncodeOfString(strDiffEncoding, "UTF-16"));
            System.out.println(strDiffEncoding + " encode in UTF-16BE output:  " + getColoredHexEncodeOfString(strDiffEncoding, "UTF-16BE"));
            System.out.println(strDiffEncoding + " encode in UTF-16LE output:  " + getColoredHexEncodeOfString(strDiffEncoding, "UTF-16LE"));
        }
    }
           

輸出如下:

JAVA控制台輸入(Scanner)及輸出顔色

從這個結果可以看出,當一個字元在編碼中不存在,找不到映射時,這個字元就會被映射為問号。

繼續閱讀