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

后端 未结 9 1882
时光说笑
时光说笑 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).

提交回复
热议问题