Various ways to write on Console
When we launch an application using java.exe using command prompt at that time, cmd.exe will be our parent application. So, in this tutorial we gonna learn various techniques to send some data to parent(command prompt) application. A stream object is available with us by default which is named as: System.out where by System is the class of java.lang package.
System.out is the object of java.io.PrintStream class. And it’s capable enough to send any kind of data to console or File. So in most of the case we don’t go for any other option. But still as a part of “Various ways to write on console”, we gonna discuss several method of writing data on console/command prompt. You can see the list of methods here.
PrintStream – System.out
import java.util.*; class SODemo { public static void main(String[] s) { System.out.println(1); // println(int) System.out.println(1.2f); // println(float) System.out.println(1.2); // println(double) System.out.println("Ankit"); // println(String) System.out.println('c'); // println(char) System.out.println(new Date()); // println(Object) System.out.println(new myOPClass(9)); // println(Object) } } class myOPClass { int x = 0; myOPClass(int x) { this.x = x; } public String toString() { return "Value of X: "+x; } }
Note: PrintStream is derived from OutputStream class of java.io package. PrintStream is a Filtered Output Stream.
OutputStream + System.out
As discussed, OutputStream is the parent class of PrintStream. So a object of PrintStream class can be referenced by OutputStream.
import java.io.*; class OSDemo { public static void main(String[] s)throws Exception { String str = "I wanna print this!"; byte[] b = str.getBytes(); OutputStream os = System.out; os.write(b); } }
OutputStreamWriter + System.out
import java.io.*; class OSWDemo { public static void main(String[] s)throws Exception { String str = "I wanna print this!"; OutputStream os = System.out; OutputStreamWriter osw = new OutputStreamWriter(os); osw.write("Ankit Virparia\n\n"); osw.flush(); osw.write(str, 2,11); osw.flush(); } }
BufferedWriter + OutputStreamWriter + System.out
import java.io.*; class BufferedWriterDemo { public static void main(String[] s)throws Exception { String str = "I wanna print this!"; OutputStream os = System.out; OutputStreamWriter osw = new OutputStreamWriter(os); BufferedWriter bw = new BufferedWriter(osw); bw.write("Ankit Virparia\n\n"); bw.flush(); bw.write(str, 2,11); bw.flush(); } }
Console
import java.io.*; class ConsoleWriteDemo { public static void main(String[] s) { Console con = System.console(); PrintWriter ps = con.writer(); ps.print("Good Morning!"); ps.println(); con.writer().println("Hi"); } }
Recent Comments