Home  >  Core Java

Java PrintStream and PrintWriter Example

By Arvind Rai, July 19, 2014
In this page we are providing the examples of java.io.PrintStream and java.io.PrintWriter classes. java.io.PrintStream has been introduced in JDK 1.0 and PrintWriter has been introduced in JDK 1.1.

PrintStream

PrintStream is subclass of OutputStream that adds extra functionality to print different type of data. PrintStream never throws IOException. PrintStream is automatically flushed when a byte array is written.
PrintStreamDemo.java
package com.cp.io;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
public class PrintStreamDemo {
	public static void main(String[] args) {
		  //Write data on console using PrintStream
		  PrintStream psConsole = new PrintStream(System.out);	
		  try {
			psConsole.write("Data to Write on Console using PrintStream".getBytes());
		  } catch (IOException e) {
				e.printStackTrace();
		  }
		  psConsole.flush();
		  psConsole.close();
		  
		  //Write data in file using PrintStream
		  PrintStream pwFile=null;
	  	  try {
	  		 pwFile = new PrintStream(new File("D:/cp/text.txt"));
	  		 pwFile.write("Data to Write in File using PrintStream".getBytes());
	 		 pwFile.flush();
		  } catch (IOException e) {
				e.printStackTrace();
		  }finally{
			  pwFile.close();
		  }
	} 	  
} 
Find the Output.
Data to Write on Console using PrintStream 

PrintWriter

PrintWriter is the implementation of Writer class. PrintWriter is used to print formatted representation to text-output-stream. PrintWriter can also be enabled for automatic flush whenever a newline character is written.
PrintWriterDemo.java
package com.cp.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class PrintWriterDemo {
	public static void main(String[] args) {
	  //Write data on console using PrintWriter
	  PrintWriter pwConsole = new PrintWriter(System.out);	
	  pwConsole.write("Data to Write on Console using PrintWriter");
	  pwConsole.flush();
	  pwConsole.close();
	  
	  //Write data in file using PrintWriter
	  PrintWriter pwFile=null;
  	  try {
  		 pwFile = new PrintWriter(new File("D:/cp/text.txt"));
  		 pwFile.write("Data to Write in File using PrintWriter");
 		 pwFile.flush();
	  } catch (FileNotFoundException e) {
			e.printStackTrace();
	  }finally{
		  pwFile.close();
	  }
 	}
} 
Find the Output.
Data to Write on Console using PrintWriter 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us