Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between FileInputStream and BufferedInputStream in Java? [closed]

Tags:

java

What is the difference between FileInputStream and BufferedInputStream in Java?

like image 354
Rohit Avatar asked Feb 08 '14 03:02

Rohit


2 Answers

Key differences:

  • BufferedInputStream is buffered, but FileInputStream is not.

  • A BufferedInputStream reads from another InputStream, but a FileInputStream reads from a file1.

In practice, this means that every call to FileInputStream.read() will perform a syscall (expensive) ... whereas most calls to BufferedInputStream.read() will return data from the buffer. In short, if you are doing "small" reads, putting a BufferedInputStream into your stream stack will improve performance.

  • For most purposes / use-cases, that is all that is relevant.

  • There are a few other things (like mark / reset / skip) but these are rather specialist ...

  • For more detailed information, read the javadocs ... and the source code.


1 - Or more precisely, from some object that 1) has a name in the operating system's "file system" namespace, and 2) that the operating system allows you to read as a sequence of bytes. This may encompass devices, named pipes, and various other things that one might not consider as "files". It is also worth noting that there some kinds of things that definitely cannot be read using a FileInputStream.

like image 117
Stephen C Avatar answered Sep 20 '22 14:09

Stephen C


You must google for that or read Javadocs,

public class FileInputStream
extends InputStream

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.

FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

For more details: https://docs.oracle.com/javase/7/docs/api/java/io/FileInputStream.html.

public class BufferedInputStream
extends FilterInputStream

A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods. When the BufferedInputStream is created, an internal buffer array 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. The mark operation remembers a point in the input stream and the reset operation causes all the bytes read since the most recent mark operation to be reread before new bytes are taken from the contained input stream.

For more details https://docs.oracle.com/javase/7/docs/api/java/io/BufferedInputStream.html.

like image 38
Rajendra arora Avatar answered Sep 19 '22 14:09

Rajendra arora