console.writeline和System.out.println [英] console.writeline and System.out.println
问题描述
console.writeline
和 System.out.println
之间的技术差异究竟是什么?
我知道 System.out.println
写入标准输出,但这与控制台不同吗?
What exactly is the technical difference between console.writeline
and System.out.println
?
I know that System.out.println
writes to standard output but is this not the same thing as the console?
我不完全理解 console.writeline 的htmlrel =noreferrer>文档。
I do not fully understand the documentation for console.writeline
.
推荐答案
以下是使用 System.out
/ .err
/ .in
和 System.console()
:
Here are the primary differences between using System.out
/.err
/.in
and System.console()
:
-
如果您的应用程序未在终端中运行,System.console()
将返回null(虽然你可以在你的应用程序中处理这个问题)。 -
System.console()
提供读取密码而不回显字符的方法 -
System.out
和System.err
使用默认平台编码,而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 charactersSystem.out
andSystem.err
use the default platform encoding, while theConsole
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 = { "\u250C\u2500\u2500\u2500\u2500\u2500\u2510",
"\u2502Hello\u2502",
"\u2514\u2500\u2500\u2500\u2500\u2500\u2518" };
for (String s : data) {
System.out.println(s);
}
for (String s : data) {
System.console().writer().println(s);
}
}
}
在我的Windows XP上Windows-1252的系统编码和IBM850的默认控制台编码,此代码将写入:
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│
└─────┘
请注意,此行为取决于将控制台编码设置为与系统编码不同的编码。由于一系列历史原因,这是Windows上的默认行为。
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.
这篇关于console.writeline和System.out.println的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!