Here are the primary differences between using System.out
/.err
/.in
and System.console()
:
System.console()
returns null if your application is not run in a terminal (though you can handle this in your application)
System.console()
provides methods for reading password without echoing characters
System.out
and System.err
use the default platform encoding, while the Console
class output methods use the console encoding
This latter behaviour may not be immediately obvious, but code like this can demonstrate the difference:
public class ConsoleDemo {
public static void main(String[] args) {
String[] data = { "u250Cu2500u2500u2500u2500u2500u2510",
"u2502Hellou2502",
"u2514u2500u2500u2500u2500u2500u2518" };
for (String s : data) {
System.out.println(s);
}
for (String s : data) {
System.console().writer().println(s);
}
}
}
On my Windows XP which has a system encoding of windows-1252 and a default console encoding of IBM850, this code will write:
???????
?Hello?
???????
┌─────┐
│Hello│
└─────┘
Note that this behaviour depends on the console encoding being set to a different encoding to the system encoding. This is the default behaviour on Windows for a bunch of historical reasons.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…