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

后端 未结 9 1710
时光说笑
时光说笑 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:38

    It will depend on your environment. If you're running a Swing UI via javaw for example, then there isn't a console to display. If you're running within an IDE, it will very much depend on the specific IDE's handling of console IO.

    From the command line, it should be fine though. Sample:

    import java.io.Console;
    
    public class Test {
    
        public static void main(String[] args) throws Exception {
            Console console = System.console();
            if (console == null) {
                System.out.println("Unable to fetch console");
                return;
            }
            String line = console.readLine();
            console.printf("I saw this line: %s", line);
        }
    }
    

    Run this just with java:

    > javac Test.java
    > java Test
    Foo  <---- entered by the user
    I saw this line: Foo    <---- program output
    

    Another option is to use System.in, which you may want to wrap in a BufferedReader to read lines, or use Scanner (again wrapping System.in).

    0 讨论(0)
  • 2020-11-22 09:38

    The following takes athspk's answer and makes it into one that loops continually until the user types "exit". I've also written a followup answer where I've taken this code and made it testable.

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class LoopingConsoleInputExample {
    
       public static final String EXIT_COMMAND = "exit";
    
       public static void main(final String[] args) throws IOException {
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          System.out.println("Enter some text, or '" + EXIT_COMMAND + "' to quit");
    
          while (true) {
    
             System.out.print("> ");
             String input = br.readLine();
             System.out.println(input);
    
             if (input.length() == EXIT_COMMAND.length() && input.toLowerCase().equals(EXIT_COMMAND)) {
                System.out.println("Exiting.");
                return;
             }
    
             System.out.println("...response goes here...");
          }
       }
    }
    

    Example output:

    Enter some text, or 'exit' to quit
    > one
    one
    ...response goes here...
    > two
    two
    ...response goes here...
    > three
    three
    ...response goes here...
    > exit
    exit
    Exiting.
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 09:42
    Scanner in = new Scanner(System.in);
    
    int i = in.nextInt();
    String s = in.next();
    
    0 讨论(0)
  • 2020-11-22 09:48

    There are few ways to read input string from your console/keyboard. The following sample code shows how to read a string from the console/keyboard by using Java.

    public class ConsoleReadingDemo {
    
    public static void main(String[] args) {
    
        // ====
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Please enter user name : ");
        String username = null;
        try {
            username = reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("You entered : " + username);
    
        // ===== In Java 5, Java.util,Scanner is used for this purpose.
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter user name : ");
        username = in.nextLine();      
        System.out.println("You entered : " + username);
    
    
        // ====== Java 6
        Console console = System.console();
        username = console.readLine("Please enter user name : ");   
        System.out.println("You entered : " + username);
    
    }
    }
    

    The last part of code used java.io.Console class. you can not get Console instance from System.console() when running the demo code through Eclipse. Because eclipse runs your application as a background process and not as a top-level process with a system console.

    0 讨论(0)
  • 2020-11-22 09:52

    Use System.in

    http://www.java-tips.org/java-se-tips/java.util/how-to-read-input-from-console.html

    0 讨论(0)
提交回复
热议问题