Java - PrintStream example

Posted on November 7, 2016


A PrintStream class provides additional functionality to write formatted data to underlying output stream.  All characters printed by the PrintStream are converted into bytes using the platform's default character encoding.

A PrintStream class never throws an IOException, it provides a method , also kwon as checkError(), to check internal error state of underlying output stream.

The flush method of the PrintStream class is automatically invoked after a byte array is written , one of the println() methods is invoked, or a newline character or byte ('\n') is written.

Here is an example to demonstrate the PrintStream class.

PrintStreamExample.java

package com.boraji.tutorial.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Date;

/**
 * @author imssbora
 */
public class PrintStreamExample {
	public static void main(String[] args) {
		File file=new File("file.txt");
		FileOutputStream fileOutputStream=null;
		PrintStream printStream=null;
		try {
			fileOutputStream=new FileOutputStream(file);
			printStream=new PrintStream(fileOutputStream);
			
			//Print char value
			printStream.print('A');
			
			//Print long value
			printStream.print(100L);
			
			//Print double value
			printStream.print(45.451);
			
			//Print date
			printStream.print(new Date());
			
			//Print newline
			printStream.println();
			
			//Print String
			printStream.println("This an example of the PrintStream class");
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(fileOutputStream!=null){
					fileOutputStream.close();
				}
				if(printStream!=null){
					printStream.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

Output file (file.txt)

A10045.451Mon Nov 07 23:56:56 IST 2016
This an example of the PrintStream class