Skip to content

I/O Streams

🔹 What are I/O Streams?

📘 Definition:

In Java, I/O Streams are used to read data from a source (like a file, keyboard, network) or write data to a destination.

  • An input stream reads data.
  • An output stream writes data.

Streams provide a continuous flow of data — like water flowing through a pipe.


🔹 Types of Streams in Java

Java divides streams mainly into two categories based on the type of data:

Stream Type Description Classes Example
Byte Streams Handle raw binary data (8-bit) InputStream, OutputStream, FileInputStream, FileOutputStream
Character Streams Handle characters (16-bit Unicode) Reader, Writer, FileReader, FileWriter

🔹 Stream Hierarchy (Simplified)

           InputStream (abstract)
          /             \
 FileInputStream     BufferedInputStream

           OutputStream (abstract)
          /              \
 FileOutputStream   BufferedOutputStream


           Reader (abstract)
          /           \
 FileReader     BufferedReader

           Writer (abstract)
          /            \
 FileWriter    BufferedWriter

🔹 Why Two Types? Byte vs Character Streams

  • Byte streams are for all data types (binary files, images, audio).
  • Character streams are designed for text data (strings, text files) and handle Unicode automatically.

🔹 Basic I/O Stream Operations

Reading bytes from a file

import java.io.FileInputStream;
import java.io.IOException;

public class ByteStreamExample {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("input.txt")) {
            int data;
            while ((data = fis.read()) != -1) {
                System.out.print((char) data);  // casting byte to char for display
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Writing bytes to a file

import java.io.FileOutputStream;
import java.io.IOException;

public class ByteWriteExample {
    public static void main(String[] args) {
        String data = "Hello, I/O Streams!";
        try (FileOutputStream fos = new FileOutputStream("output.txt")) {
            fos.write(data.getBytes());  // write string as bytes
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

🔹 Buffered Streams

  • Wrap around file streams to improve efficiency by reducing the number of I/O operations.
  • Read/write data in chunks (buffers), which is faster than byte-by-byte.

Example:

BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line = br.readLine();

🔹 Other Important Stream Classes

Class Purpose
DataInputStream Read primitive Java data types from a stream
DataOutputStream Write primitive Java data types
ObjectInputStream Read Java objects (deserialization)
ObjectOutputStream Write Java objects (serialization)

📝 Common Exam Questions

  1. What is an I/O stream in Java?
  2. Difference between byte streams and character streams.
  3. How to read and write files using streams?
  4. What is buffering and why is it used?

✅ Summary

Aspect Description
I/O Stream Flow of data for input/output
Byte Streams Read/write raw bytes (binary data)
Character Streams Read/write characters (text data)
Buffered Streams Use buffer to improve efficiency
Common Classes FileInputStream, FileOutputStream, FileReader, FileWriter

File Streams

🔹 What are File Streams?

📘 Definition:

File Streams are specialized streams in Java used to read data from files or write data to files.

  • File streams provide a way to connect a program to a file on the filesystem for input/output operations.
  • They are subclasses of InputStream/OutputStream (for bytes) and Reader/Writer (for characters).

🔹 Types of File Streams in Java

1. Byte-oriented file streams

  • Used for handling raw binary data (images, audio, executable files).
  • Main classes:

  • FileInputStream — reads bytes from a file.

  • FileOutputStream — writes bytes to a file.

2. Character-oriented file streams

  • Used for reading/writing text data (strings, characters).
  • Main classes:

  • FileReader — reads characters from a file.

  • FileWriter — writes characters to a file.

🔹 How to Use File Streams?

Reading from a file (byte stream)

import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamExample {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("input.dat")) {
            int byteRead;
            while ((byteRead = fis.read()) != -1) {
                System.out.print((char) byteRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Writing to a file (byte stream)

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamExample {
    public static void main(String[] args) {
        String data = "Hello, File Streams!";
        try (FileOutputStream fos = new FileOutputStream("output.dat")) {
            fos.write(data.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Reading from a file (character stream)

import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample {
    public static void main(String[] args) {
        try (FileReader fr = new FileReader("input.txt")) {
            int ch;
            while ((ch = fr.read()) != -1) {
                System.out.print((char) ch);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Writing to a file (character stream)

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample {
    public static void main(String[] args) {
        String data = "Hello, character streams!";
        try (FileWriter fw = new FileWriter("output.txt")) {
            fw.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

🔹 Important Features of File Streams

Feature Description
FileInputStream Reads bytes one at a time or into a byte array
FileOutputStream Writes bytes to a file
FileReader Reads characters (Unicode)
FileWriter Writes characters (Unicode)
File Not Found Handling Throws FileNotFoundException if file doesn't exist
Closing Streams Always close streams to free system resources (try-with-resources recommended)

🔹 Buffering with File Streams

  • Reading/writing byte-by-byte or char-by-char is inefficient.
  • Use buffered streams for better performance:
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
  • Buffers reduce the number of disk access operations by reading/writing chunks of data.

🔹 Exception Handling

  • File stream operations throw IOException which must be handled.
  • Always use try-with-resources or finally blocks to close streams.

🔹 Summary

Concept Description
File Streams Read/write data to/from files
Byte Streams FileInputStream, FileOutputStream
Character Streams FileReader, FileWriter
Buffering Use BufferedReader and BufferedWriter for efficiency
Exception Handling Handle IOException, close streams properly

Java Applets

🔹 What is a Java Applet?

📘 Definition:

A Java Applet is a special type of Java program that runs inside a web browser (or an applet viewer). It is designed to provide interactive features to web applications that cannot be done with just HTML.

  • It is a small application embedded in an HTML page.
  • It runs in a sandboxed environment for security.
  • It can have a graphical user interface (GUI).

🔹 History and Context

  • Introduced in the early days of Java for creating dynamic and interactive web content.
  • Applets run in browsers with Java plugin support.
  • Over time, due to security issues and evolving web standards (like JavaScript, HTML5), applets became deprecated.
  • Modern browsers no longer support applets, but understanding them is useful for legacy systems and exams.

🔹 How Does an Applet Work?

  • An applet is a subclass of the abstract class java.applet.Applet (or javax.swing.JApplet for Swing-based).
  • The browser or applet viewer loads the applet class and calls its lifecycle methods.
  • Runs in a restricted security context (sandbox).

🔹 Basic Structure of an Applet

import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorldApplet extends Applet {

    // Called when applet is first loaded
    public void init() {
        // Initialization code
    }

    // Called every time the applet is started or restarted
    public void start() {
        // Start or resume execution
    }

    // Called to repaint the applet window
    public void paint(Graphics g) {
        g.drawString("Hello, Applet!", 20, 20);
    }

    // Called when applet is stopped
    public void stop() {
        // Pause execution, release resources
    }

    // Called when applet is destroyed
    public void destroy() {
        // Cleanup before applet is removed
    }
}

🔹 Applet Lifecycle Methods

Method When is it called? Purpose
init() Once, when the applet is loaded Initialize applet
start() Each time applet becomes active Start or resume activities
paint() When applet needs to redraw Display or update graphics
stop() When applet is no longer visible Pause ongoing activities
destroy() Before applet is removed or browser closes Final cleanup

🔹 How to Embed an Applet in HTML

<applet code="HelloWorldApplet.class" width="300" height="150"></applet>
  • code specifies the compiled .class file.
  • width and height specify display area.

Note: Modern browsers no longer support the <applet> tag; the <object> tag was sometimes used instead.


🔹 Security Restrictions

  • Applets run in a sandbox to prevent malicious behavior.
  • Cannot access local files on the client machine.
  • Cannot execute native code or system commands.
  • Network access is limited to the server from which the applet was loaded.

🔹 Advantages of Applets (When Used)

  • Platform-independent (runs on any browser with JVM).
  • Easy to embed interactive content inside web pages.
  • Good for learning event handling and GUI programming.

🔹 Disadvantages and Limitations

  • Requires Java plugin installed and enabled in browser.
  • Security restrictions limit functionality.
  • Performance issues compared to native apps.
  • Deprecated and unsupported in modern web browsers.

🔹 Applet vs Application

Feature Applet Application
Runs in Browser or applet viewer JVM standalone
User interface Embedded in web page Separate window/application
Security Sandbox restrictions Full system access
Execution Managed by browser/plugin Run directly on OS

📝 Common Exam Questions

  1. What is a Java applet?
  2. Describe the lifecycle methods of an applet.
  3. How do you embed an applet in an HTML page?
  4. What are the security restrictions of applets?
  5. Differences between applets and applications.

✅ Summary

Topic Details
Definition Small Java program embedded in web pages
Lifecycle init(), start(), paint(), stop(), destroy()
Embedding <applet> tag in HTML
Security Runs in sandbox with restricted access
Status Deprecated due to browser support ending