FileInputStream and FileOutputStream in Java

The classes FileInputStream and FileOutputStream in Java are used to perform byte-based input and output operations, specifically for reading from and writing to files. These streams are designed to handle raw data like binary files (images, videos, audio files) or any non-textual data. Unlike BufferedInputStream and BufferedOutputStream, these streams do not use any internal buffering mechanism.


FileInputStream Class

FileInputStream is a byte-based input stream used to read bytes from a file. It is commonly used when you need to process binary files, such as image files, videos, or audio files, but it can also read textual data if needed (though for text, FileReader is usually preferred).

How It Works:

  • FileInputStream reads data byte by byte directly from the file, without any internal buffer. Each call to the read() method accesses the file system, which can be slower for larger files.

Constructors of FileInputStream:

FileInputStream(String fileName) // Opens the specified file
FileInputStream(File file) // Opens a File object

Key Methods:

  • read(): Reads the next byte of data from the input stream. Returns -1 when the end of the file is reached.
  • read(byte[] b): Reads up to b.length bytes of data into the byte array b.
  • close(): Closes the input stream and releases any system resources.
Code Example

Explanation:

  • FileInputStream: Opens the file example.txt for reading.
  • fis.read(): Reads the file byte by byte. Each byte is cast to a character ((char) data) for display.
  • Output: The content of example.txt is printed to the console.

FileOutputStream Class

FileOutputStream is a byte-based output stream used to write bytes to a file. It is typically used to write binary data like images, videos, and other non-textual files, but can also be used to write textual data (though for text, FileWriter is usually preferred).

How It Works:

  • FileOutputStream writes data byte by byte directly to the file. Each call to the write() method writes the byte immediately to the file without buffering, which can be slower for frequent small writes.

Constructors of FileOutputStream:

FileOutputStream(String fileName) // Creates a new file, or opens an existing file
FileOutputStream(File file) // Writes to the specified File object
FileOutputStream(String fileName, boolean append) // Opens the file in append mode if true

Key Methods:

  • write(int b): Writes the specified byte to the output stream.
  • write(byte[] b): Writes b.length bytes from the byte array b to the file.
  • close(): Closes the output stream and releases any system resources.
Code Example
Output

Explanation:

  • FileOutputStream: Opens output.txt for writing. If the file doesn't exist, it is created.
  • fos.write(): Converts the string data to a byte array and writes it to the file.
  • Output: The file output.txt now contains the text "Hello, FileOutputStream!".