🔹 File Handling in OOP

**File Handling** is an essential feature in **Object-Oriented Programming (OOP)** that allows programs to **read, write, and manipulate files** on a storage system. It enables data persistence beyond the runtime of a program.

📌 Why Use File Handling?

File handling is crucial for **storing and retrieving data efficiently**.

  • ✅ **Data Persistence** – Stores data permanently.
  • ✅ **Efficient Data Processing** – Allows structured storage and retrieval.
  • ✅ **Interoperability** – Enables data sharing between different programs.

💡 Real-Life Example

Consider a **User Management System** that stores user details in a file and retrieves them when needed.

🖥️ File Handling in Java

In Java, file handling is performed using classes from the **java.io** package.


            import java.io.*;
            
            class FileHandler {
                public static void main(String[] args) {
                    try {
                        FileWriter writer = new FileWriter("users.txt");
                        writer.write("User1: Alice\nUser2: Bob");
                        writer.close();
            
                        BufferedReader reader = new BufferedReader(new FileReader("users.txt"));
                        String line;
                        while ((line = reader.readLine()) != null) {
                            System.out.println(line);
                        }
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
                

🖥️ File Handling in Python

In Python, file handling is done using **built-in functions** like `open()`.


            class FileHandler:
                @staticmethod
                def write_file():
                    with open("users.txt", "w") as file:
                        file.write("User1: Alice\nUser2: Bob")
            
                @staticmethod
                def read_file():
                    with open("users.txt", "r") as file:
                        for line in file:
                            print(line.strip())
            
            FileHandler.write_file()
            FileHandler.read_file()
                

🎯 Summary

**File Handling** enables programs to **store and retrieve data persistently**. It is essential for **data management, logging, and configuration storage** in software applications.

🔗 Next Topics