CACS204 Object Oriented Programming in Java

Object Oriented Programming in JavaUnit 88 min read

File Handling in Java: Streams, Files, I/O Operations

Unit 8 of Object Oriented Programming in Java covers file handling techniques in Java, including file I/O streams (byte/character), file operations (create, read, write, delete), serialization, and practical applications like data persistence and log files. This note explains concepts with visual traces, real-world exa

Core Concepts

1. File Handling Basics

File handling in Java allows programs to interact with external files for data persistence (saving/loading data beyond program execution). Key classes:

  • File (metadata like name, size, path)
  • FileReader/FileWriter (character streams)
  • FileInputStream/FileOutputStream (byte streams)
  • BufferedReader/BufferedWriter (efficient I/O)

Why it matters: Without file handling, programs cannot save user data (e.g., eSewa transaction history) or read configurations (e.g., Daraz’s product catalog).


2. Streams in Java

Streams are unidirectional channels for data transfer. Two types:

Type Use Case Classes Example
Byte Stream Raw binary data (images, executables) FileInputStream, FileOutputStream Reading a .jpg file
Character Stream Text data (UTF-8) FileReader, FileWriter Writing a .txt log file

Visual: Byte vs. Character Stream

graph LR
    A["File"] -->|"Byte Stream"| B["FileInputStream"]
    A -->|"Character Stream"| C["FileReader"]
    B --> D["Process Binary Data"]
    C --> E["Process Text Data"]

Real-world tie-in:

  • eSewa uses file streams to log transactions (character streams for text logs, byte streams for encrypted data).
  • WhatsApp stores media files (byte streams) and chat history (character streams).

3. File Operations with Code Examples

A. Creating and Writing to a File

Code:

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

public class FileWriterExample {
    public static void main(String[] args) {
        try (FileWriter writer = new FileWriter("data.txt")) {
            writer.write("Hello, TU Students!\n");
            writer.write("File handling is easy in Java.");
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Trace Table:

Step Action File State (data.txt)
1 FileWriter opens file (Created, empty)
2 write("Hello...") Hello, TU Students!
3 write("File handling...") Hello, TU Students!\nFile handling is easy in Java.

Visual: File State After Writing


B. Reading from a File

Code:

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

public class FileReaderExample {
    public static void main(String[] args) {
        try (FileReader reader = new FileReader("data.txt")) {
            int data;
            while ((data = reader.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Trace Table:

Step Action Output
1 reader.read() (first char) H
2 Loop continues e, l, l, o, ...
3 End of file (-1) Program exits

Real-world tie-in:

  • NTC’s billing system reads customer data from files (e.g., customers.txt) to generate invoices.
  • Pathao’s driver app logs ride history to a file for analytics.

C. Copying a File (Byte Stream Example)

Code:

import java.io.*;

public class FileCopyExample {
    public static void main(String[] args) {
        try (
            FileInputStream in = new FileInputStream("source.txt");
            FileOutputStream out = new FileOutputStream("destination.txt")
        ) {
            int byteData;
            while ((byteData = in.read()) != -1) {
                out.write(byteData);
            }
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Visual: File Copy Process

flowchart LR
    A["source.txt"] -->|"FileInputStream"| B["Read Byte"]
    B --> C["Write Byte"] --> D["destination.txt"]

Exam Tip:

  • Always close streams using try-with-resources to avoid memory leaks.
  • For large files, use buffered streams (BufferedInputStream, BufferedOutputStream) for efficiency.

4. Serialization (Saving Objects to Files)

Serialization converts objects into byte streams for storage/transmission. Key Classes:

  • ObjectOutputStream (write objects)
  • ObjectInputStream (read objects)

Example: Saving a Student Object

import java.io.*;

class Student implements Serializable {
    String name;
    int rollNo;
    Student(String name, int rollNo) {
        this.name = name;
        this.rollNo = rollNo;
    }
}

public class SerializationExample {
    public static void main(String[] args) {
        Student student = new Student("Ramesh", 101);
        try (
            FileOutputStream fos = new FileOutputStream("student.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos)
        ) {
            oos.writeObject(student);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Visual: Serialization Process

graph LR
    A["Student Object"] --> B["ObjectOutputStream"]
    B --> C["Byte Stream"] --> D["student.ser File"]

Real-world tie-in:

  • Khalti serializes transaction records to ensure data integrity across servers.
  • Nepal Rastra Bank uses serialization to archive financial reports securely.

5. Handling Exceptions in File Operations

Common exceptions:

  • FileNotFoundException: File doesn’t exist.
  • IOException: General I/O errors (e.g., disk full).

Example: Safe File Reading

try {
    FileReader reader = new FileReader("nonexistent.txt");
    // Code...
} catch (FileNotFoundException e) {
    System.err.println("File not found! Using default data.");
} catch (IOException e) {
    System.err.println("I/O Error: " + e.getMessage());
}

Exam Tip:

  • Always handle exceptions for file operations. Use try-catch blocks or declare throws IOException.

In the Real World

  1. eSewa:

    • Uses file streams to log transactions (e.g., transactions_2024.txt) for auditing.
    • Serialization stores user profiles (user_123.ser) for quick retrieval.
  2. Daraz:

    • Byte streams handle product images (.jpg, .png) in the catalog.
    • Character streams manage text-based inventory data (products.csv).
  3. NTC Billing System:

    • FileReader reads customer details from customers.dat to generate bills.
    • BufferedWriter writes usage logs (usage_2024.log) for analytics.

Exam Tip

  1. Code Structure:

    • Always use try-with-resources for streams.
    • Example starter:
      try (FileWriter fw = new FileWriter("file.txt")) {
          fw.write("Exam Tip: Handle exceptions!");
      } catch (IOException e) {
          System.out.println("Error: " + e);
      }
      
  2. Common Questions:

    • Differentiate byte/character streams: Ask about binary vs. text data.
    • Serialization: Explain how objects are converted to bytes and back.
    • Exception handling: Show try-catch for FileNotFoundException.
  3. Practical Task:

    • Write a program to copy a file (use FileInputStream/FileOutputStream).
    • Bonus: Add error handling for non-existent source files.

Key Formulas/Shortcuts:

Task Code Snippet
Write to file FileWriter fw = new FileWriter("file.txt");
Read from file FileReader fr = new FileReader("file.txt");
Serialize object ObjectOutputStream oos = new ObjectOutputStream(fos);
Deserialize object ObjectInputStream ois = new ObjectInputStream(fis);

Visual Summary of File Operations

mindmap
  root((File Handling in Java))
    Streams
      Byte Stream
        FileInputStream
        FileOutputStream
      Character Stream
        FileReader
        FileWriter
    Operations
      Create
      Read
      Write
      Delete
    Serialization
      ObjectOutputStream
      ObjectInputStream
    Exceptions
      FileNotFoundException
      IOException

Based on the TU BCA syllabus for Object Oriented Programming in Java (CACS204), unit 8.

Discussion

Loading…