Programing

console.writeline 및 System.out.println

crosscheck 2020. 7. 24. 07:36
반응형

console.writeline 및 System.out.println


정확히 사이의 기술적 차이 무엇 console.writelineSystem.out.println? 나는 그것이 System.out.println표준 출력에 쓰는 것을 알고 있지만 이것은 콘솔과 같은 것이 아닙니까?

에 대한 설명서완전히 이해하지 못합니다 console.writeline.


여기에 사용 사이의 주요 차이점입니다 System.out/ .err/.inSystem.console():

  • System.console()응용 프로그램이 터미널에서 실행되지 않으면 null을 반환합니다 (응용 프로그램에서 처리 할 수는 있지만 )
  • System.console() 문자를 에코하지 않고 비밀번호를 읽는 방법을 제공합니다.
  • System.out그리고 System.err그동안 기본 플랫폼 인코딩을 사용하는 Console클래스 출력 방법은 콘솔 인코딩을 사용

후자의 행동은 즉시 명백하지 않을 수도 있지만, 이와 같은 코드는 차이점을 보여줄 수 있습니다.

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-1252의 시스템 인코딩과 IBM850의 기본 콘솔 인코딩이있는 Windows XP에서이 코드는 다음과 같이 작성됩니다.

???????
?Hello?
???????
┌─────┐
│Hello│
└─────┘

이 동작은 시스템 인코딩과 다른 인코딩으로 설정되는 콘솔 인코딩에 따라 다릅니다. 여러 가지 역사적 이유로 Windows의 기본 동작입니다.


프로그램이 대화식 프롬프트에서 실행되고 stdin 또는 stdout을 리디렉션하지 않은 경우 기본적으로 동일합니다.

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

결과 :

$ java ConsoleTest
Console is: java.io.Console@2747ee05
$ java ConsoleTest </dev/null
Console is: null
$ java ConsoleTest | cat
Console is: null

그 이유 Console는 대화 형 명령 줄에서 실행중인 특정 경우에 유용한 기능을 제공하기위한 것입니다.

  • 안전한 비밀번호 입력 (플랫폼 간 어려운 작업)
  • 동기화 (여러 스레드가 입력을 요구할 수 Console있고 잘 큐잉하는 반면 System.in/out을 사용하면 모든 프롬프트가 동시에 나타납니다).

스트림 중 하나 라도 리디렉션 하면 결과가 System.console()반환됩니다 null. 또 다른 자극은 ConsoleEclipse 또는 Maven과 같은 다른 프로그램에서 생성 될 때 사용할 수있는 객체 가 없다는 것 입니다.


먼저 귀하의 질문에 약간의 실수가 포함되어 있습니다. 클래스 콘솔에는 메소드 쓰기 라인이 없습니다. 대신 클래스 콘솔은 PrintWriter를 반환하는 메소드 writer ()를 제공합니다. 이 인쇄기에는 println ()이 있습니다.

이제 차이점은 무엇입니까

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

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.


There's no Console.writeline in Java. Its in .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

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.

참고URL : https://stackoverflow.com/questions/4005378/console-writeline-and-system-out-println

반응형