Output Stream Writer Example Java Program


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.


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");
			System.out.println("" + (char) ins.read());
			System.out.println("Stream is being closed");
			System.out.println("Stream closed successfully.");
		} catch (Exception e) {

Sample Output

Output is:
Stream is being closed
Stream closed successfully.