SrcForge

Lesson 55

InputStream and OutputStream

InputStream and OutputStream are fundamental Java I/O classes used for reading and writing byte-oriented data. FileInputStream and FileOutputStream are their concrete subclasses for working with files.

Java Track

Save progress as you learn.

61 lessons

Lesson content

InputStream and OutputStream are fundamental Java I/O classes used for reading and writing data. Input streams read data from a source, while output streams write data to a destination such as a file, array, socket, or peripheral device.

What are Streams in Java?

A stream is a sequence of data that flows between a program and a data source or destination. Java uses streams to perform input and output (I/O) operations.

Types of Streams

  • InputStream – Reads data from a source.
  • OutputStream – Writes data to a destination.

Key Terms

  • Stream: A flow of data between a program and a source or destination.
  • InputStream: A class used to read byte-oriented data.
  • OutputStream: A class used to write byte-oriented data.
  • Byte Stream: A stream that processes data one byte at a time.
  • FileInputStream: A class used to read data from a file.
  • FileOutputStream: A class used to write data to a file.

Java OutputStream Class

The OutputStream class is an abstract class that serves as the superclass of all byte output stream classes. It is used to send data to a destination such as files, arrays, network sockets, or peripheral devices.

OutputStream Class Hierarchy

OutputStream

 ├── FileOutputStream
 ├── ByteArrayOutputStream
 ├── BufferedOutputStream
 └── ObjectOutputStream

Useful Methods of OutputStream

MethodDescription
write(int)Writes a byte to the output stream
write(byte[])Writes an array of bytes
flush()Flushes the output stream
close()Closes the output stream
// write(int) - Writes a single byte
outputStream.write(65);

// write(byte[]) - Writes an array of bytes
outputStream.write(data);

// flush() - Forces any buffered data to be written immediately
outputStream.flush();

// close() - Closes the stream and releases resources
outputStream.close();

Java InputStream Class

The InputStream class is an abstract class that serves as the superclass of all byte input stream classes. It is used to read data from sources such as files, arrays, network sockets, or peripheral devices.

InputStream Class Hierarchy

InputStream

 ├── FileInputStream
 ├── ByteArrayInputStream
 ├── BufferedInputStream
 └── ObjectInputStream

Useful Methods of InputStream

MethodDescription
read()Reads a byte of data
available()Returns available bytes
close()Closes the stream
// read() - Reads the next byte from the stream
// Returns byte value (0-255), or -1 at end of file
inputStream.read();

// available() - Returns the estimated number of bytes available
inputStream.available();

// close() - Closes the stream
inputStream.close();

Java FileInputStream Class

FileInputStream is a subclass of InputStream used for reading data from files. It reads data byte by byte.

Features of FileInputStream

  • Reads file content
  • Supports binary files
  • Reads byte-oriented data
  • Suitable for images, text files, and documents

Example: Reading a File Using FileInputStream

package com.java.FileStream;
import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamExample {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            // Open the file
            fis = new FileInputStream("example.txt");
            
            int content;
            // Read the file until the end
            while ((content = fis.read()) != -1) {
                // Convert byte to character and print
                System.out.print((char) content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Close the file input stream
            try {
                if (fis != null) fis.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

How FileInputStream Works

  • Step 1: Open the File — fis = new FileInputStream("example.txt"); creates a connection to the file.
  • Step 2: Read Data — while ((content = fis.read()) != -1) reads one byte at a time until the end of the file.
  • Step 3: Convert Bytes to Characters — System.out.print((char) content); displays the file content.
  • Step 4: Close the Stream — fis.close(); releases system resources.

Sample File Content

Hello Java Streams

Output

Hello Java Streams

Java FileOutputStream Class

FileOutputStream is a subclass of OutputStream used to write data to files. It can write text data, binary data, primitive values, and character data converted to bytes.

Features of FileOutputStream

  • Creates files
  • Writes data to files
  • Supports byte-oriented output
  • Can overwrite existing files

Example: Writing Data Using FileOutputStream

package com.java.FileStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamExample {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            // Open the file in write mode (will overwrite if file exists)
            fos = new FileOutputStream("output.txt");

            String content = "This is an example of FileOutputStream in Java.";
            
            // Write the string content to the file as bytes
            fos.write(content.getBytes());
            
            System.out.println("File written successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Close the file output stream
            try {
                if (fos != null) fos.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

How FileOutputStream Works

  • Step 1: Create or Open the File — fos = new FileOutputStream("output.txt"); opens the file for writing.
  • Step 2: Convert Text to Bytes — content.getBytes(); converts the string into a byte array.
  • Step 3: Write Data — fos.write(content.getBytes()); writes the bytes into the file.
  • Step 4: Close the Stream — fos.close(); ensures all data is saved and resources are released.

Output

Console Output:
File written successfully!

File Content (output.txt):
This is an example of FileOutputStream in Java.

InputStream vs OutputStream

FeatureInputStreamOutputStream
PurposeRead dataWrite data
DirectionSource → ProgramProgram → Destination
Base ClassInputStreamOutputStream
Common SubclassFileInputStreamFileOutputStream
Main Methodread()write()

Advantages of Using Streams in Java

  • Efficient Data Transfer — allows smooth reading and writing of data.
  • Supports Multiple Sources — works with files, sockets, arrays, and devices.
  • Flexible Architecture — provides many specialized stream classes.
  • Foundation of Java I/O — most Java I/O operations are based on streams.

Best Practices

  • Always close streams using close() to release resources.
  • Handle exceptions properly by wrapping stream operations inside try-catch blocks.
  • Use a finally block to ensure streams are closed even when exceptions occur.
  • Check for end of file by always verifying read() does not return -1.
  • Consider buffered streams (BufferedInputStream, BufferedOutputStream) for better performance.

FAQ

1. What is the difference between InputStream and OutputStream in Java?

InputStream reads data from a source, while OutputStream writes data to a destination.

2. What does the read() method return?

The read() method returns the next byte of data or -1 when the end of the file is reached.

3. Why should streams be closed after use?

Closing streams releases system resources, prevents memory leaks, and ensures data is properly saved.

InputStream and OutputStream are abstract superclasses for byte-oriented Java I/O.
OutputStream writes data to destinations like files, arrays, sockets, or devices.
InputStream reads data from sources like files, arrays, sockets, or devices.
FileInputStream and FileOutputStream are concrete subclasses for file-based I/O.
read() returns -1 at end of file; always close streams in a finally block.
Buffered streams (BufferedInputStream, BufferedOutputStream) improve performance.

Where Java is used

Java in real-world development

InputStream

Abstract superclass for reading byte-oriented data from a source such as a file, array, socket, or device.

OutputStream

Abstract superclass for writing byte-oriented data to a destination such as a file, array, socket, or device.

FileInputStream

Subclass of InputStream used to read byte data from files, suitable for text, binary, and image files.

FileOutputStream

Subclass of OutputStream used to write byte data to files; can create or overwrite files.

read()

Reads the next byte from an input stream; returns -1 when end of file is reached.

write(byte[])

Writes an array of bytes to an output stream, such as a file.

Prev: Date and Time APIBack to hub