BufferedInputStream and BufferedOutputStream in java

In the previous post, we have seen FileInputStream and FileOutputStream. In this post, we will look at BufferedInputStream and BufferedOutputStream in java.

Let’s start with BufferedOutputStream class.

BufferedOutputStream class:

BufferedOutputStream class uses an internal buffer to store the data first. Rather than writing one byte at a time to the destination file, stored data in a buffer will be written at a time. It is not required to make a system call for each byte written, hence speed up writing.

This is typically much faster , can be used for disk access and large amount of data. To add buffering to outputStream , simply add it through BufferedOutputStream. Let’s look at the example below for understanding.

public class FileHandlingEx {
	public static void main(String[] args){		
		 try {
		   FileOutputStream fout=new FileOutputStream("Sample.txt");  
		   BufferedOutputStream bfrout=new BufferedOutputStream(fout);  
		   String s="My laptop is working good";  
		   byte b[]=s.getBytes();  
		  
		   bfrout.write(b);
		   bfrout.flush();  
		   bfrout.close();  
		   fout.close(); 
		} catch (IOException e) {
			e.printStackTrace();
		}  
 
		   System.out.println("Write task successful");  
	}	
}
Output: Write task successful

BufferedInputStream:

BufferedInputStream class is used to provide buffering to inputStream. Instead of reading one byte at a time, it can read a large block of data. It improves the reading performance.

Example of BufferedInputStream:

public class FileHandlingEx {
	public static void main(String[] args){		
		  try{  
			    FileInputStream fin=new FileInputStream("Sample.txt");  
			    BufferedInputStream bin=new BufferedInputStream(fin);  
			    int i;  
			    while((i=bin.read())!=-1){  
			     System.out.println((char)i);  
			    }  
			    bin.close();  
			    fin.close();  
			  }catch(Exception e){
				  System.out.println(e);
			  }  
		   } 	
}
Output: My laptop is working good
Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.

 

 

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

1 Response

  1. August 8, 2015

    […] the previous post, we have seen BufferedInputStream and BufferedOutputStream. In this post, we will CharArrayWriter […]