Java console.writeline 和 System.out.println

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4005378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 08:13:22  来源:igfitidea点击:

console.writeline and System.out.println

javaio

提问by ziggy

What exactly is the technical difference between console.writelineand System.out.println? I know that System.out.printlnwrites to standard output but is this not the same thing as the console?

console.writeline和之间的技术区别究竟是什么System.out.println?我知道System.out.println写入标准输出,但这与控制台不同吗?

I do not fully understand the documentationfor console.writeline.

我不完全理解的文档进行console.writeline

采纳答案by McDowell

Here are the primary differences between using System.out/.err/.inand System.console():

下面是使用的主要区别System.out/ .err/.inSystem.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.outand System.erruse the default platform encoding, while the Consoleclass output methods use the console encoding
  • System.console()如果您的应用程序未在终端中运行,则返回 null(尽管您可以在您的应用程序中处理此问题
  • System.console()提供不回显字符读取密码的方法
  • System.outSystem.err使用默认平台编码,而Console类输出方法使用控制台编码

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);
    }
  }
}

On my Windows XP which has a system encoding of windows-1252 and a default console encoding of IBM850, this code will write:

在我的系统编码为 windows-1252 和默认控制台编码为 IBM850 的 Windows XP 上,此代码将写入:

???????
?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.

请注意,此行为取决于将控制台编码设置为与系统编码不同的编码。由于一系列历史原因,这是 Windows 上的默认行为。

回答by SimonJ

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

它们本质上是相同的,如果您的程序是从交互式提示运行的,并且您没有重定向 stdin 或 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 </dev/null
Console is: null
$ java ConsoleTest | cat
Console is: null

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

Console存在的原因是提供在您从交互式命令行运行的特定情况下有用的功能:

  • secure password entry (hard to do cross-platform)
  • synchronisation (multiple threads can prompt for input and Consolewill queue them up nicely, whereas if you used System.in/out then all of the prompts would appear simultaneously).
  • 安全密码输入(难以跨平台)
  • 同步(多个线程可以提示输入并将Console它们很好地排队,而如果您使用 System.in/out 那么所有提示将同时出现)。

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

请注意,即使重定向一个流也会导致System.console()返回null; 另一个令人恼火的是,Console当从其他程序(例如 Eclipse 或 Maven)生成时,通常没有可用的对象。

回答by Nithesh Chandra

There's no Console.writelinein Java. Its in .NET.

Console.writelineJava 中没有。它在 .NET 中。

Console and standard out are not same. If you read the Javadoc page you mentioned, you will see that an application can have access to a console only if it is invoked from the command line and the output is not redirected like this

控制台和标准输出不一样。如果您阅读了您提到的 Javadoc 页面,您将看到应用程序只有在从命令行调用并且输出不会像这样重定向时才能访问控制台。

java -jar MyApp.jar > MyApp.log

Other such cases are covered in SimonJ's answer, though he missed out on the point that there's no Console.writeline.

SimonJ 的回答中涵盖了其他此类案例,尽管他错过了没有Console.writeline.

回答by AlexR

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().

首先我担心你的问题包含一个小错误。类 Console 中没有方法 writeline。相反,类 Console 提供了返回 PrintWriter 的方法 writer()。这个打印作者有 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.

如果您从命令行运行您的应用程序,我认为没有区别。但是如果控制台不可用 System.console() 返回 null 而 System.out 仍然存在。如果您调用应用程序并将 STDOUT 重定向到文件,则可能会发生这种情况。

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...

但是当我将 STDOUT 重定向到文件时......

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

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

8号线是console.writer().println()

Here is the content of /tmp/test

这是/tmp/test的内容

console=null

I hope my explanations help.

我希望我的解释有帮助。