Java: How to get input from System.console()

后端 未结 9 1873
时光说笑
时光说笑 2020-11-22 09:08

I am trying to use Console class to get input from user but a null object is returned when I call System.console(). Do I have to change anything before using Sy

9条回答
  •  礼貌的吻别
    2020-11-22 09:41

    I wrote the Text-IO library, which can deal with the problem of System.console() being null when running an application from within an IDE.

    It introduces an abstraction layer similar to the one proposed by McDowell. If System.console() returns null, the library switches to a Swing-based console.

    In addition, Text-IO has a series of useful features:

    • supports reading values with various data types.
    • allows masking the input when reading sensitive data.
    • allows selecting a value from a list.
    • allows specifying constraints on the input values (format patterns, value ranges, length constraints etc.).

    Usage example:

    TextIO textIO = TextIoFactory.getTextIO();
    
    String user = textIO.newStringInputReader()
            .withDefaultValue("admin")
            .read("Username");
    
    String password = textIO.newStringInputReader()
            .withMinLength(6)
            .withInputMasking(true)
            .read("Password");
    
    int age = textIO.newIntInputReader()
            .withMinVal(13)
            .read("Age");
    
    Month month = textIO.newEnumInputReader(Month.class)
            .read("What month were you born in?");
    
    textIO.getTextTerminal().println("User " + user + " is " + age + " years old, " +
            "was born in " + month + " and has the password " + password + ".");
    

    In this image you can see the above code running in a Swing-based console.

提交回复
热议问题