0

How come that System.out.println("Hello World") prints to console?

out is a static variable of type PrintStream. On out you call println(). How come it prints to console? Is that a default channel? Could I also say print to a file ?

saw303
  • 8,051
  • 7
  • 50
  • 90
Julia19
  • 15
  • 5
  • Here is a solutin: https://www.baeldung.com/java-write-to-file But is it java? You are sure ? It looks like C++ – Bartosz Olchowik Feb 21 '20 at 12:39
  • Yes, System.out == console. – Amongalen Feb 21 '20 at 12:40
  • You could probably reassign the out by using `System.setOut(PrintStream out)` provided that the SecurityManager for your JVM allows this. Typically writing to a file is done differently, like Bartosz said. – Jan Held Feb 21 '20 at 12:41
  • `PrintStream` wraps an `OutputStream`. And stdout is an ostream/`OutputStream` – Rogue Feb 21 '20 at 12:42
  • System.out represents stdout "Stdout, also known as standard output, is the default file descriptor where a process can write output." https://www.programcreek.com/java-api-examples/?api=java.lang.System.Logger – Tarun Gupta Feb 21 '20 at 12:43
  • Since Java 9, the standard way of logging your log statements to a file is by using System.Logger - https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/System.Logger.html – Tarun Gupta Feb 21 '20 at 12:45

2 Answers2

0

Yes. The console is the default output stream. In order to write to file using the system.out.println() command you need to change the output stream.

PrintStream fileOut = new PrintStream("./out.txt");
System.setOut(fileOut);
System.out.println("this write in file");

egjlmn1
  • 324
  • 3
  • 11
  • Ok. so variable out is from Type PrintStream . I thought PrintStream is only for Files . So how can it be default to console. Console is not a file. – Julia19 Feb 21 '20 at 13:57
  • No, PrintStream is not only for the file. PrintStream adds few functionalities to its super class, OutputStream. There is Another OutputStream called FileOutputStream which is made for files. To create a PrintStream that can write to files you need to do something like this: new PrintStream(new FileOutputStream("Engineer.txt")); – egjlmn1 Feb 22 '20 at 14:07
0

out is instantiated during startup and gets mapped to the standard output console of the host (which is the console by default).

You can change the out object, e.g. instead of standard output to write to a file, using the setOut method:

System.setOut(new PrintStream(new FileOutputStream("log.txt")));
System.out.println("Writing to log.txt");
vs97
  • 5,765
  • 3
  • 28
  • 41