Program to Read text from file using BufferedInputStream (and FileInputStream) in java file IO

BufferedInputStream >
  • BufferedInputStream is buffered.
  • BufferedInputStream reads bytes from another InputStream (Eg - FileInputStream)
  • when BufferedInputStream.read() is called mostly data is read from the buffer. When data is not available available in buffer a call is made to read system file and lot of bytes are kept in buffer.
  • A BufferedInputStream enables another input stream to buffer the input and supports the mark and reset methods. An internal buffer array is created when the BufferedInputStream is created. As bytes from the stream are read or skipped, the internal buffer is refilled as necessary from the contained input stream, many bytes at a time.
  • BufferedInputStream is much faster as compared to FileInputStream.


We will read c:/myFile.txt

c:/myFile.txt looks like this >
You are learning File IO from javaMadeSoEasy.com




Program to Read text from file using FileInputStream and BufferedInputStream in java file IO >
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

/** JavaMadeSoEasy.com */
public class ReadFileUsingBufferedInputStream {
   public static void main(String... args) {
          FileInputStream fis = null;
          BufferedInputStream bis = null;
         
          try {
                 fis = new FileInputStream("c:/myFile.txt");
                 bis= new BufferedInputStream(fis);
                
                 System.out.println("Reading from text file using BufferedInputStream > ");
                 int ch;
                 while ((ch = bis.read()) != -1) { //read till end of file
                       System.out.print((char) ch);
                 }
          } catch (IOException e) {
                 e.printStackTrace();
          } finally {
             try {
                       if (bis != null)
                              bis.close(); //close BufferedInputStream
                                            // will close FileInputStream
                 } catch (IOException e) {
                       e.printStackTrace();
                 }
          }
   }
}
/*OUTPUT
Reading from text file using BufferedInputStream >
You are learning File IO from javaMadeSoEasy.com   
*/




RELATED LINKS>

Read text from file using BufferedInputStream (and FileInputStream) in java file IO


Difference between FileInputStream and BufferedInputStream in java file IO


Program to Read text from file in String using BufferedInputStream (and FileInputStream) in java file IO


Should we close both FileInputStream and BufferedInputStream ? OR BufferedReader and FileReader ?


eEdit
Must read for you :