console.writeline and System.out.println

后端 未结 4 695
一生所求
一生所求 2020-11-28 21:50

What exactly is the technical difference between console.writeline and System.out.println? I know that System.out.println writes to s

4条回答
  •  星月不相逢
    2020-11-28 22:12

    First I am afraid your question contains a little mistake. There is not method writeline in class Console. Instead class Console provides method writer() that returns PrintWriter. This print writer has println().

    Now what is the difference between

    System.console().writer().println("hello from console");
    

    and

    System.out.println("hello system out");
    

    If you run your application from command line I think there is no difference. But if console is unavailable System.console() returns null while System.out still exists. This may happen if you invoke your application and perform redirect of STDOUT to file.

    Here is an example I have just implemented.

    import java.io.Console;
    
    
    public class TestConsole {
        public static void main(String[] args) {
            Console console = System.console();
            System.out.println("console=" + console);
            console.writer().println("hello from console");
        }
    }
    

    When I ran the application from command prompt I got the following:

    $ java TestConsole
    console=java.io.Console@93dcd
    hello from console
    

    but when I redirected the STDOUT to file...

    $ java TestConsole >/tmp/test
    Exception in thread "main" java.lang.NullPointerException
            at TestConsole.main(TestConsole.java:8)
    

    Line 8 is console.writer().println().

    Here is the content of /tmp/test

    console=null
    

    I hope my explanations help.

提交回复
热议问题