Output Stream Writer Example Java Program

Definition

The OutputStream class is an abstract superclass that provides a minimal programming interface and a partial implementation of output streams. OutputStream defines methods for writing bytes or arrays of bytes to the stream. An output stream is automatically opened when you create it. You can explicitly close an output stream with the close method, or let it be closed implicitly when the OutputStream is garbage collected, which occurs when the object is no longer referenced. the OutputStreamWriter is used along with OutputStream.

Syntax

OutputStream Variable_name1 = new FileOutputStream(File_location);
OutputStreamWriter Variable_name2 = new OutputStreamWriter(Variable_name1);

Output Stream Writer Example Program

import java.io.*;

public class OutputStreamWriterDemo {
	public static void main(String[] args) {
		try {
			OutputStream out = new FileOutputStream("newfile.txt");
			OutputStreamWriter outw = new OutputStreamWriter(out);
			FileInputStream ins = new FileInputStream("newfile.txt");
			outw.write(70);
			outw.flush();
			System.out.println("" + (char) ins.read());
			System.out.println("Stream is being closed");
			outw.close();
			System.out.println("Stream closed successfully.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Sample Output

Output is:
F
Stream is being closed
Stream closed successfully.