console.writeline and System.out.println

后端 未结 4 690
一生所求
一生所求 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:05

    They're essentially the same, if your program is run from an interactive prompt and you haven't redirected stdin or stdout:

    public class ConsoleTest {
        public static void main(String[] args) {
            System.out.println("Console is: " + System.console());
        }
    }
    

    results in:

    $ java ConsoleTest
    Console is: java.io.Console@2747ee05
    $ java ConsoleTest 

    The reason Console exists is to provide features that are useful in the specific case that you're being run from an interactive command line:

    • secure password entry (hard to do cross-platform)
    • synchronisation (multiple threads can prompt for input and Console will queue them up nicely, whereas if you used System.in/out then all of the prompts would appear simultaneously).

    Notice above that redirecting even one of the streams results in System.console() returning null; another irritation is that there's often no Console object available when spawned from another program such as Eclipse or Maven.

提交回复
热议问题