File I/O in java - streams (Input/output), Readers/Writers, Buffered

Streams - Input/output

  • Stream is Byte Based, Input stream can be used to read bytes, output stream can be used to write bytes.
  • Stream is used to binary input/output. Eg- Java .class file
  • Read or write 1 byte (8-bit) at a time
  • Streams can be handy for machine-oriented data.


  • Reader/Writers is Character Based, it can be used to read or write characters.
  • Reader is used to character input/output
  • Example -
    • FileReader is used for reading text files in platform default encoding.
    • Now question comes comes, What is Platform default encoding?
      • Platform default encoding means the encoding used by the operating system on which  the JVM is running.
    • Example - Platform default encoding is user specific setting.
      • Windows (in US) - it's often CP1250,
      • Windows (in Europe) - it's often CP1252.
      • Windows (in China) - it's often Big5.
  • Read or write 2 bytes(16-bit) at a time, because char is 16-bit data type.

Buffered - Like BufferedInputStream and BufferedOutputStream | BufferedReader and BufferedWriter

  • Buffered is buffered, it's faster and hence improves performance.

FileInputStream fis = new FileInputStream("c:/myFile.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
  • 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.
when 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.

Example -

A BufferedInputStream reads from FileInputStream, will request lot of data from the FileInputStream (128 bytes or so… not exact figure). Thus only 2 calls will be made for reading 256 bytes from file.
Another Example - Real world Example - You must have seen youtube videos where video is buffered before you actually start watching it, buffering overall improves your video watching experience.


Difference between Stream (FileInputStream) and Reader (FileReader) in java file

Difference between FileInputStream and BufferedInputStream in java file IO

Must read for you :