Java - File Input Output Buffered Read

Introduction

BufferedInputStream adds buffer to an input stream.

It maintains an internal buffer to store bytes read from the underlying input stream.

BufferedInputStream reads more bytes than requested and buffers them in its buffer.

When a byte read is requested, it checks if the requested byte already exists in its buffer.

It supports mark and reset operations on an input stream to let you reread bytes from an input stream.

BufferedInputStream is faster because of buffering.

The following code demonstrates how to use a BufferedInputStream to read contents of a file.

In BufferedFileReading, you construct the input stream as follows:

String srcFile = "Main.java";
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));

Demo

import java.io.BufferedInputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    String srcFile = "Main.java";

    try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
        srcFile))) {//  w  ww  .j  a  v  a  2 s.c om
      // Read one byte at a time and display it
      byte byteData;
      while ((byteData = (byte) bis.read()) != -1) {
        System.out.print((char) byteData);
      }
    } catch (FileNotFoundException e1) {
      FileUtil.printFileNotFoundMsg(srcFile);
    } catch (IOException e2) {
      e2.printStackTrace();
    }
  }
}

class FileUtil {
  // Prints the location details of a file
  public static void printFileNotFoundMsg(String fileName) {
    String workingDir = System.getProperty("user.dir");
    System.out.println("Could not find the file '" + fileName + "' in '"
        + workingDir + "' directory ");
  }

  // Closes a Closeable resource such as an input/output stream
  public static void close(Closeable resource) {
    if (resource != null) {
      try {
        resource.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

Result