Java - BufferedInputStream and BufferedOutputStream example

Posted on November 5, 2016


BufferedInputStream and BufferedOutputStream use an internal array of byte, also known as buffer, to store data while reading and writing, respectively. Buffered streams are typically more efficient than similar non-buffered streams.

Here is an example to demonstrate BufferedInputStream.

BufferedInputStreamExample.java

package com.boraji.tutorial.io;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author imssbora BufferedInputStreamExample.java Nov 5, 2016
 */
public class BufferedInputStreamExample {
	public static void main(String[] args) {
		File file = new File("file.txt");
		FileInputStream fileInputStream = null;
		BufferedInputStream bufferedInputStream = null;

		try {
			fileInputStream = new FileInputStream(file);
			bufferedInputStream = new BufferedInputStream(fileInputStream);
			// Create buffer
			byte[] buffer = new byte[1024];
			int bytesRead = 0;
			while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
				System.out.println(new String(buffer, 0, bytesRead));
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fileInputStream != null) {
					fileInputStream.close();
				}
				if (bufferedInputStream != null) {
					bufferedInputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}
}

Output

This is an example of reading data from file using BufferedInputStream.

 

Following is an example to demonstrate BufferedOutputStream.

BufferedOutputStreamExample.java

package com.boraji.tutorial.io;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author imssbora
 * BufferedOutputStreamExample.java
 * Nov 5, 2016
 */
public class BufferedOutputStreamExample {
	public static void main(String[] args) {
		File file=new File("outfile.txt");
		FileOutputStream fileOutputStream=null;
		BufferedOutputStream bufferedOutputStream=null;
		try {
			fileOutputStream=new FileOutputStream(file);
			bufferedOutputStream=new BufferedOutputStream(fileOutputStream);
			bufferedOutputStream.write("This is an example of writing data to a file".getBytes());
			bufferedOutputStream.write(" using BufferedOutputStream".getBytes());
			bufferedOutputStream.flush();
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(fileOutputStream!=null){
					fileOutputStream.close();
				}
				if(bufferedOutputStream!=null){
					bufferedOutputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Output - outfile.txt

This is an example of writing data to a file using BufferedOutputStream