How to Write Data to Console in Java

Read this tutorial.

In Java, System.out.println(), System.out.print() and System.out.write() are the most widely used functions used to write data to console. Many of the programs in this blog also do the same.

However the usage of these methods should be restricted to output of simple programs as System.out is a byte stream. As a thumb rule restrict usage of System.out for debugging purposes and output of very small programs.

For large programs it is recommended to use character based stream as it makes it easier to internationalize your program. In Java, data can be written to console as character stream using the PrintWriter class. Below is one of the many methods that this PrintWriter class provides


1
PrintWriter(OutputStream out,booleanautoFlush)


Above function creates a new PrintWriter from an existing output stream and performs automatic flushing when newline is encountered.

 

Program to write data to console using PrintWriter class


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
packagecom.codewithabhi.console;
importjava.io.PrintWriter;
publicclassStringConsoleOutput{
/**
* @param Program to write data to standard console
*/
publicstaticvoidmain(String[]args){
PrintWriter pw=newPrintWriter(System.out,true);
pw.println("Writing data to console using PrintWriter class.");
pw.println(1);
pw.println(13.0D);
pw.close();
}
}


Output


1
2
3
Writing data toconsole using PrintWriter class.
1
13.0

 


Source: Abhishek Kumar, http://web.archive.org/web/20160210174050/http://codewithabhi.com/2013/06/how-to-write-data-to-console-in-java.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 License.

Last modified: Thursday, April 18, 2019, 3:26 PM