Java Code Example for BufferedOutputStream to Write OutputStream

BufferedOutputStream can be setup to write the bytes to the underlying output stream without necessarily causing call to the underlying system for each byte written.

BufferedOutputStream class has below two constructor :

  • BufferedOutputStream(OutputStream out) – Creates a new buffered output stream to write data to the specified underlying output stream.
  • BufferedOutputStream(OutputStream out, int size) – Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size.

BufferedOutputStream class inherits below methods from class java.io.FilterOutputStream :

  • write()
  • close()

Below is the code example which show how to use BufferedOutputStream to write to System.out stream –

/**********************************************************************************
 * Created on Nov, 2004 Copyright(c) https://kodehelp.com All Rights Reserved.
 **********************************************************************************/
package com.kodehelp.java.io.BufferedOutputStream;

import java.io.BufferedOutputStream;
import java.io.IOException;

/**
 * @author https://kodehelp.com
 *
 */
public class BufferedOpStream {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		BufferedOutputStream bos =null;
		try{
			bos = new BufferedOutputStream(System.out);
			byte[] b = new byte[26];
			for(int i=0; i<26 ; i++){
				b[i]= (byte) (i+65);
			}

			bos.write(b, 0, 26);
		}catch(IOException ioe){
			System.out.println("Error while writing to System OutStream" + ioe);
		}finally{
			try
			{
				if(bos != null)
				{
					bos.flush();
					bos.close();
				}

			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
}

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.