Java File Handling Explained in Depth: Read and Write Files with Examples

Java File Handling Explained in Depth

Author: Gursehbaj Singh | Blog: DevMode

File Handling in Java allows us to create, read, write, and delete files. It is very important for real-world applications such as saving data, logging, and reading configuration files.

Why File Handling is Important?

  • Store data permanently
  • Read user information from files
  • Create logs and reports
  • Work with databases and backups

Java File Class

The File class is used to represent a file or directory.


import java.io.File;

File file = new File("example.txt");

Creating a File


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

class CreateFile {
    public static void main(String[] args) {
        try {
            File file = new File("myfile.txt");
            if (file.createNewFile()) {
                System.out.println("File created successfully");
            } else {
                System.out.println("File already exists");
            }
        } catch (IOException e) {
            System.out.println("Error while creating file");
        }
    }
}

Writing to a File

We use FileWriter to write data into a file.


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

class WriteFile {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("myfile.txt");
            writer.write("Welcome to DevMode Java File Handling");
            writer.close();
            System.out.println("Data written successfully");
        } catch (IOException e) {
            System.out.println("Error while writing to file");
        }
    }
}

Reading from a File

We use FileReader and Scanner to read data.


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

class ReadFile {
    public static void main(String[] args) {
        try {
            File file = new File("myfile.txt");
            Scanner sc = new Scanner(file);
            while (sc.hasNextLine()) {
                String data = sc.nextLine();
                System.out.println(data);
            }
            sc.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        }
    }
}

Appending Data to File


FileWriter writer = new FileWriter("myfile.txt", true);
writer.write("\nLearning Java is fun!");
writer.close();

Deleting a File


File file = new File("myfile.txt");
if (file.delete()) {
    System.out.println("File deleted");
} else {
    System.out.println("Failed to delete file");
}

BufferedWriter for Fast Writing


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

BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"));
bw.write("Buffered writing in Java");
bw.close();

BufferedReader for Fast Reading


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

BufferedReader br = new BufferedReader(new FileReader("data.txt"));
String line;
while((line = br.readLine()) != null) {
    System.out.println(line);
}
br.close();

Exception Handling in File Handling

Always handle IOExceptions to avoid program crash.

Best Practices

  • Always close files after use
  • Use try-with-resources
  • Handle exceptions properly
  • Do not hardcode file paths

Conclusion

File handling is a core skill in Java. By learning how to create, read, write, append, and delete files, you can build real applications like text editors, log systems, and data storage programs.

Comments

Popular posts from this blog

Top 10 Free Coding Websites Every Beginner Should Use in 2026

Graph Data Structure – Complete Beginner to Advanced Guide with BFS, DFS and Examples

5 JavaScript Console Methods You're Not Using (But Should Be)