BufferedInputStream

how can I use BufferedInputStream?

The BufferedInputStream class provides buffering to your input streams. Buffering can speed up IO quite a bit. Rather than read one byte at a time from the network or disk, the BufferedInputStream reads a larger block at a time. This is typically much faster, especially for disk access and larger data amounts

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;

public class BufferedInputStreamDemo {
public static void main(String[] args) throws Exception {

  InputStream inStream = null;
  BufferedInputStream bis = null;
  
  try{
   
     inStream = new FileInputStream("c:/test.txt");

   
     bis = new BufferedInputStream(inStream);			

  
     while(bis.available()>0)
     {
      
        char c = (char)bis.read();

       
        System.out.println("Char: "+c);;
     }
  }catch(Exception e){
    
     e.printStackTrace();
  }finally{		
     // releases any system resources associated with the stream
     if(inStream!=null)
        inStream.close();
     if(bis!=null)
        bis.close();
  }

}
}

If you are consistently doing small reads then a BufferedInputStream will give you significantly better performance. Each read request on an unbuffered stream typically results in a system call to the operating system to read the requested number of bytes. The overhead of doing a system call is may be thousands of machine instructions per syscall. A buffered stream reduces this by doing one large read for (say) up to 8k bytes into an internal buffer, and then handing out bytes from that buffer. This can drastically reduce the number of system calls.

However, if you are consistently doing large reads (e.g. 8k or more) then a BufferedInputStream slows things. You typically don’t reduce the number of syscalls, and the buffering introduces an extra data copying step.
Example

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

public class BufferedInputStreamExample {

public static void main(String[] args) {

	File file = new File("C:\\testing.txt");
	FileInputStream fis = null;
	BufferedInputStream bis = null;
	DataInputStream dis = null;

	try {
		fis = new FileInputStream(file);

		bis = new BufferedInputStream(fis);
		dis = new DataInputStream(bis);

		while (dis.available() != 0) {
			System.out.println(dis.readLine());
		}

	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		try {
			fis.close();
			bis.close();
			dis.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}

}

//