File Handling

Section 4: File Handling

Lesson 1: Working with Files in Java

1.1 Reading and Writing to Files

File handling in Java involves reading from and writing to files. The java.nio.file package provides classes for file operations.

Example (Reading from a File): 

import java.nio.file.*;

import java.io.IOException;

import java.util.List;


public class ReadFileExample {

    public static void main(String[] args) {

        // Path to the file

        Path filePath = Paths.get("example.txt");


        try {

            // Reading all lines from the file

            List<String> lines = Files.readAllLines(filePath);


            // Displaying the content

            for (String line : lines) {

                System.out.println(line);

            }

        } catch (IOException e) {

            System.out.println("An error occurred while reading the file: " + e.getMessage());

        }

    }

}

Example (Writing to a File):

import java.nio.file.*;

import java.io.IOException;

import java.util.Arrays;

import java.util.List;


public class WriteFileExample {

    public static void main(String[] args) {

        // Path to the file

        Path filePath = Paths.get("output.txt");


        // Content to write to the file

        List<String> content = Arrays.asList("Line 1", "Line 2", "Line 3");


        try {

            // Writing content to the file

            Files.write(filePath, content);


            System.out.println("Content written to the file successfully.");

        } catch (IOException e) {

            System.out.println("An error occurred while writing to the file: " + e.getMessage());

        }

    }

}


1.2 Handling Exceptions Related to File Operations

When working with files, it's crucial to handle potential exceptions to ensure robust and error-resistant code.

Example (Exception Handling): 

import java.nio.file.*;

import java.io.IOException;


public class FileHandlingWithExceptions {

    public static void main(String[] args) {

        // Path to the file

        Path filePath = Paths.get("example.txt");


        try {

            // Reading from the file

            List<String> lines = Files.readAllLines(filePath);


            // Displaying the content

            for (String line : lines) {

                System.out.println(line);

            }

        } catch (IOException e) {

            System.out.println("An error occurred while reading the file: " + e.getMessage());

        }

    }

}


Lesson 2: Serialization and Deserialization

2.1 Saving and Loading Java Objects

Serialization allows you to convert Java objects into a format that can be easily stored or transmitted. Deserialization is the reverse process of recreating objects from this format.

Example (Serialization and Deserialization):

import java.io.*;

class Student implements Serializable {

    String name;

    int age;


    public Student(String name, int age) {

        this.name = name;

        this.age = age;

    }

}


public class SerializationExample {

    public static void main(String[] args) {

        // Serialization

        try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("student.ser"))) {

            Student student = new Student("John Doe", 20);


            // Writing object to file

            outputStream.writeObject(student);


            System.out.println("Object serialized and saved to file.");

        } catch (IOException e) {

            System.out.println("An error occurred during serialization: " + e.getMessage());

        }


        // Deserialization

        try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("student.ser"))) {

            // Reading object from file

            Student loadedStudent = (Student) inputStream.readObject();


            System.out.println("Object deserialized: " + loadedStudent.name + ", Age: " + loadedStudent.age);

        } catch (IOException | ClassNotFoundException e) {

            System.out.println("An error occurred during deserialization: " + e.getMessage());

        }

    }

}

File handling, including reading, writing, serialization, and deserialization, is essential for many Java applications. Practice these examples to become proficient in handling files and managing data persistence.