File Handling in Java

Introduction

In the previous lesson, we explored Exception Handling, which helps in managing errors and ensuring program stability. Now, we move on to File Handling in Java, a fundamental concept for reading from and writing to files efficiently.

Reading and Writing Files

Java provides classes such as FileReader and FileWriter to handle file operations.

Writing to a File

Writing to a file means saving data (text or binary) from a program to a file on the computer’s storage. This allows information to persist beyond the program’s execution. Example using FileWriter .

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

class FileWriteExample {
    public static void main(String[] args) {
        try (FileWriter writer = new FileWriter("example.txt")) {
            writer.write("Hello, Java File Handling!");
            System.out.println("File written successfully.");
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}

Reading from a File

Reading from a file is the opposite of writing to a file. It involves reading data (text or binary) from a file on the computer’s storage into a running Java program. Example using FileReader .

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

class FileReadExample {
    public static void main(String[] args) {
        try (FileReader reader = new FileReader("example.txt")) {
            int ch;
            while ((ch = reader.read()) != -1) {
                System.out.print((char) ch);
            }
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}

BufferedReader & BufferedWriter

These are are classes in Java that provide efficient reading and writing of text files by using buffering.

Writing with BufferedWriter

This class writes text to an output stream efficiently by buffering characters before writing. It improves performance over direct writing methods such as the FileWriter.

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

class BufferedWriterExample {
    public static void main(String[] args) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("buffered_example.txt"))) {
            writer.write("Buffered writing in Java.");
            System.out.println("Buffered write completed.");
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}

Reading with BufferedReader

The BufferedReader class reads text from an input stream efficiently by buffering characters. It also improves performance over direct reading methods such as the FileReader.

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

class BufferedReaderExample {
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader("buffered_example.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}

File Handling Best Practices

  • Always close file streams or use try-with-resources.

  • Handle exceptions properly to avoid crashes.

  • Use buffering for efficient file operations and when performance matters.

  • Check if a file exists before reading or writing to avoid errors.

Conclusion

File handling in Java enables reading and writing data efficiently. Using FileReader, FileWriter, BufferedReader, and BufferedWriter, we can handle files effectively while following best practices to ensure robustness. Mastering file handling is crucial for developing applications that interact with stored data.

Stay tuned for the next topic in the Java Short Notes series!

0
Subscribe to my newsletter

Read articles from Emmanuel Enchill directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Emmanuel Enchill
Emmanuel Enchill

I am a passionate software engineer in training at ALX. I have a strong preference for back-end development. I am on course to share my learning journey with you.