AdSense

AdSense3

Wednesday, 5 November 2014

Java BufferedOutputStream and BufferedInputStream

Java BufferedOutputStream class

Java BufferedOutputStream class uses an internal buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.

Example of BufferedOutputStream class:

In this example, we are writing the textual information in the BufferedOutputStream object which is connected to the FileOutputStream object. The flush() flushes the data of one stream and send it into another. It is required if you have connected the one stream with another.
  1. import java.io.*;  
  2. class Test{  
  3.  public static void main(String args[])throws Exception{  
  4.    FileOutputStream fout=new FileOutputStream("f1.txt");  
  5.    BufferedOutputStream bout=new BufferedOutputStream(fout);  
  6.    String s="Sachin is my favourite player";  
  7.    byte b[]=s.getBytes();  
  8.    bout.write(b);  
  9.   
  10.    bout.flush();  
  11.    bout.close();  
  12.    fout.close();  
  13.    System.out.println("success");  
  14.  }  
  15. }   
Output:
success...

Java BufferedInputStream class

Java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make the performance fast.

Example of Java BufferedInputStream

Let's see the simple example to read data of file using BufferedInputStream.
  1. import java.io.*;  
  2. class SimpleRead{  
  3.  public static void main(String args[]){  
  4.   try{  
  5.     FileInputStream fin=new FileInputStream("f1.txt");  
  6.     BufferedInputStream bin=new BufferedInputStream(fin);  
  7.     int i;  
  8.     while((i=bin.read())!=-1){  
  9.      System.out.println((char)i);  
  10.     }  
  11.     bin.close();  
  12.     fin.close();  
  13.   }catch(Exception e){system.out.println(e);}  
  14.  }  
  15. }  
Output:
Sachin is my favourite player

No comments:

Post a Comment