+ 1
Can we use console.printf instead of system.out.println . Because i use console.printf
what is difference between this two
1 Réponse
+ 7
Class Console provides method writer() that returns PrintWriter. This print writer has 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.
Here is an example -
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