File Handling in Java

Chapter 10: File Handling in Java | Read, Write, Create Files


📁 Chapter 10: File Handling in Java

File handling in Java is essential when dealing with data storage and retrieval in the form of text or binary files. Java offers various classes and methods in the java.io and java.nio packages to handle files.

🔹 Why File Handling is Important?

  • To store data persistently
  • To read configuration or input data from external files
  • To generate logs and reports
  • To handle user uploads/downloads

📦 Java File Handling Classes

  • File – Represents a file or directory
  • FileWriter – For writing text to files
  • FileReader – For reading text files
  • BufferedReader – Reads text efficiently, line by line
  • BufferedWriter – Writes text efficiently
  • Scanner – Reads file content easily with parsing capabilities

📂 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.");
            e.printStackTrace();
        }
    }
}
  

📝 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 writing!");
            writer.close();
            System.out.println("Successfully wrote to the file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  

📖 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) {
            e.printStackTrace();
        }
    }
}
  

❌ 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("Deleted the file: " + file.getName());
        } else {
            System.out.println("Failed to delete the file.");
        }
    }
}
  

⚠️ 5. Handling Exceptions

Always use try-catch blocks to handle IOException and FileNotFoundException while working with files.

🔍 Summary of File Handling in Java

  • File: Creates, deletes, checks info
  • FileWriter: Writes characters to file
  • FileReader/BufferedReader: Reads file efficiently
  • Always close file streams: Use .close() method or try-with-resources

❓ FAQs about Java File Handling

Q1: What is the difference between FileWriter and BufferedWriter?

A: FileWriter writes characters directly, while BufferedWriter adds buffering for performance improvement by reducing I/O operations.

Q2: Why do we need to close file streams in Java?

A: Closing a stream ensures that all data is flushed properly and system resources are released to avoid memory leaks.

Q3: Can we write both text and binary data using FileWriter?

A: No. FileWriter is designed for character (text) data. Use FileOutputStream for binary data.

Q4: How can we check if a file exists before reading?

A: Use File.exists() method before reading to avoid FileNotFoundException.

Q5: What happens if we try to delete a file that doesn’t exist?

A: The File.delete() method will return false, and the file will not be deleted.

Q6: How do we append data instead of overwriting?

A: Pass true as the second parameter in the FileWriter constructor: new FileWriter("file.txt", true);

Q7: Can we read/write files in Java without using exceptions?

A: File I/O involves external systems (disk, OS) and always requires exception handling using try-catch.


Author: Op Verma | Category: Java Programming

Tags: Java File Handling, Java IO, Java FileWriter, Java FileReader, BufferedReader Java

📌 Related Links: Complete Java Course

Comments

Popular posts from this blog

Best AI Tools for Students and Professionals in 2025 | Boost Learning & Productivity

Introduction to Java

Top AI Tools for Content Creators: Bloggers, YouTubers & Writers (2025)