DEV Community

Jayashree
Jayashree

Posted on

File Handling in Java – Complete Guide

File Handling in Java

File handling in Java allows us to create, read, write, and delete files. It is an essential concept when working with data storage outside the program.

What is File Handling?

File handling means performing operations on files such as:

  • Creating a file
  • Writing data to a file
  • Reading data from a file
  • Deleting a file

Java provides classes in the java.io package to perform these operations.

Important Classes in Java File Handling

  • File → Represents a file or directory
  • FileWriter → Writes data to a file
  • FileReader → Reads data from a file
  • BufferedReader → Reads text efficiently
  • BufferedWriter → Writes text efficiently

1. Creating a File

import java.io.File;
import java.io.IOException;

public class CreateFileExample {
    public static void main(String[] args) {
        try {
            File file = new File("example.txt");
            if (file.createNewFile()) {
                System.out.println("File created: " + file.getName());
            } else {
                System.out.println("File already exists");
            }
        } catch (IOException e) {
            System.out.println("An error occurred");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Writing to a File

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

public class WriteFileExample {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("example.txt");
            writer.write("Hello, this is Java file handling!");
            writer.close();
            System.out.println("Successfully written to file.");
        } catch (IOException e) {
            System.out.println("Error writing file");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Reading from a File

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

public class ReadFileExample {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
            String line;

            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            reader.close();
        } catch (IOException e) {
            System.out.println("Error reading file");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

FileReader vs BufferedReader

Feature FileReader BufferedReader
Reading Style Character by character Line by line
Speed Slower Faster
Efficiency Low (no buffering) High (uses buffer)
Use Case Small files Large files
Memory Usage Less Slightly more (buffer used)

4. Deleting a File

import java.io.File;

public class DeleteFileExample {
    public static void main(String[] args) {
        File file = new File("example.txt");

        if (file.delete()) {
            System.out.println("File deleted successfully");
        } else {
            System.out.println("Failed to delete file");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Exception Handling in File Handling

File operations may cause errors such as:

  • File not found
  • Permission issues
  • I/O errors

So we use try-catch blocks to handle exceptions like IOException.

Advantages of File Handling

  • Stores data permanently
  • Helps in data sharing
  • Useful for logs, reports, and configuration files

** Conclusion**

File handling in Java is a powerful feature that allows programs to interact with external files. By using classes like File, FileWriter, and BufferedReader, we can easily manage file operations efficiently.

Top comments (0)