Java File Handling

Learn to create, read, write, and manage files in Java - because data needs a permanent home beyond RAM!

What is File Handling?

File handling in Java allows you to create, read, write, update, and delete files stored on your computer. It's essential for saving data permanently, as variables only exist while the program runs.

Think of file handling like organizing documents in filing cabinets - you can create new files, read existing ones, add content, or throw them away when not needed!

  • Create files: Make new files on disk
  • Write data: Save information to files
  • Read data: Retrieve information from files
  • Delete files: Remove files when no longer needed

💡 Why File Handling? Save user data, store logs, create reports, backup information - files make data persistent across program runs!

Important Java File Classes

  • File: Represents a file or directory, used to create, check existence, delete files
  • FileWriter: Writes text data to files (character streams)
  • FileReader: Reads text data from files character by character
  • BufferedReader: Reads text efficiently line by line
  • Scanner: Reads and parses data from files easily
  • FileInputStream/FileOutputStream: For reading/writing binary data (bytes)

📦 Import Required: All file classes are in java.io package, so always import: import java.io.*;

Creating a File

Let's start by creating a new file using the File class:

Example: Create a New File

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

public class Main {
    public static void main(String[] args) {
        try {
            // Create a File object
            File myFile = new File("student.txt");
            
            // Create the file
            if (myFile.createNewFile()) {
                System.out.println("File created: " + myFile.getName());
                System.out.println("Absolute path: " + myFile.getAbsolutePath());
            } else {
                System.out.println("File already exists!");
            }
            
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
Output:
File created: student.txt
Absolute path: C:\Users\YourName\student.txt

Explanation:

  • File myFile = new File("student.txt") - Creates File object representing the file
  • createNewFile() - Actually creates the physical file on disk
  • Returns true if file created successfully, false if already exists
  • IOException must be handled - file operations can fail
  • getAbsolutePath() shows complete file location

Writing to a File

Use FileWriter to write text content to a file:

Example: Write Data to File

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

public class Main {
    public static void main(String[] args) {
        try {
            // Create FileWriter object
            FileWriter writer = new FileWriter("student.txt");
            
            // Write content to file
            writer.write("Name: Rahul Kumar\n");
            writer.write("Roll No: 101\n");
            writer.write("Course: Java Programming\n");
            writer.write("Marks: 95\n");
            
            // Close the writer (important!)
            writer.close();
            
            System.out.println("Successfully wrote to the file!");
            
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
Output:
Successfully wrote to the file!

Explanation:

  • FileWriter writer = new FileWriter("student.txt") - Opens file for writing
  • writer.write() - Writes text to the file
  • \n adds new line (move to next line)
  • writer.close() - MUST close writer to save changes and free resources
  • If file doesn't exist, FileWriter creates it automatically

⚠️ Important: Always close FileWriter using close() or data might not be saved! Better yet, use try-with-resources.

Reading from a File

Use Scanner class to read file content easily:

Example: Read Data from File

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

public class Main {
    public static void main(String[] args) {
        try {
            // Create File object
            File myFile = new File("student.txt");
            
            // Create Scanner to read file
            Scanner reader = new Scanner(myFile);
            
            System.out.println("Reading file content:");
            System.out.println("---------------------");
            
            // Read file line by line
            while (reader.hasNextLine()) {
                String line = reader.nextLine();
                System.out.println(line);
            }
            
            // Close the scanner
            reader.close();
            
        } catch (FileNotFoundException e) {
            System.out.println("File not found!");
            e.printStackTrace();
        }
    }
}
Output:
Reading file content:
---------------------
Name: Rahul Kumar
Roll No: 101
Course: Java Programming
Marks: 95

Explanation:

  • Scanner reader = new Scanner(myFile) - Creates scanner to read file
  • hasNextLine() - Checks if more lines exist in file
  • nextLine() - Reads one complete line from file
  • while loop continues until all lines are read
  • FileNotFoundException thrown if file doesn't exist

Appending to a File

To add content without overwriting existing data, use FileWriter with append mode:

Example: Append Data to Existing File

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

public class Main {
    public static void main(String[] args) {
        try {
            // FileWriter with 'true' parameter = append mode
            FileWriter writer = new FileWriter("student.txt", true);
            
            // Add new content to end of file
            writer.write("Grade: A+\n");
            writer.write("Status: Pass\n");
            
            writer.close();
            System.out.println("Data appended successfully!");
            
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
Output:
Data appended successfully!

Explanation:

  • new FileWriter("student.txt", true) - Second parameter true enables append mode
  • New content is added at the end of existing content
  • Without true, FileWriter overwrites the entire file
  • Perfect for logs, records that grow over time

Getting File Information

The File class provides methods to get information about files:

Example: File Information Methods

import java.io.File;

public class Main {
    public static void main(String[] args) {
        File myFile = new File("student.txt");
        
        if (myFile.exists()) {
            System.out.println("File Information:");
            System.out.println("-----------------");
            System.out.println("File name: " + myFile.getName());
            System.out.println("Absolute path: " + myFile.getAbsolutePath());
            System.out.println("Writable: " + myFile.canWrite());
            System.out.println("Readable: " + myFile.canRead());
            System.out.println("File size (bytes): " + myFile.length());
            System.out.println("Is directory: " + myFile.isDirectory());
            System.out.println("Is file: " + myFile.isFile());
        } else {
            System.out.println("File does not exist!");
        }
    }
}
Output:
File Information:
-----------------
File name: student.txt
Absolute path: C:\Users\YourName\student.txt
Writable: true
Readable: true
File size (bytes): 95
Is directory: false
Is file: true

Explanation:

  • exists() - Checks if file exists on disk
  • getName() - Returns file name
  • getAbsolutePath() - Returns complete path
  • canWrite() / canRead() - Check permissions
  • length() - Returns file size in bytes
  • isDirectory() / isFile() - Check type

Deleting a File

Remove files using the delete() method:

Example: Delete a File

import java.io.File;

public class Main {
    public static void main(String[] args) {
        File myFile = new File("student.txt");
        
        if (myFile.exists()) {
            if (myFile.delete()) {
                System.out.println("File deleted: " + myFile.getName());
            } else {
                System.out.println("Failed to delete the file.");
            }
        } else {
            System.out.println("File does not exist!");
        }
    }
}
Output:
File deleted: student.txt

Explanation:

  • delete() - Deletes the file from disk permanently
  • Returns true if successful, false otherwise
  • Always check if file exists before trying to delete
  • Deleted files cannot be recovered (no recycle bin)

⚠️ Warning: delete() permanently removes files. There's no undo! Always double-check before deleting important files.

Using Try-With-Resources

A better way to handle files - automatically closes resources:

Example: Try-With-Resources (Best Practice)

import java.io.FileWriter;
import java.io.IOException;
import java.io.File;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        
        // Writing with try-with-resources
        try (FileWriter writer = new FileWriter("data.txt")) {
            writer.write("Java File Handling\n");
            writer.write("Try-with-resources is awesome!\n");
            System.out.println("File written successfully!");
        } catch (IOException e) {
            System.out.println("Write error: " + e.getMessage());
        }
        // writer.close() called automatically!
        
        // Reading with try-with-resources
        try (Scanner reader = new Scanner(new File("data.txt"))) {
            System.out.println("\nFile content:");
            while (reader.hasNextLine()) {
                System.out.println(reader.nextLine());
            }
        } catch (IOException e) {
            System.out.println("Read error: " + e.getMessage());
        }
        // reader.close() called automatically!
    }
}
Output:
File written successfully!

File content:
Java File Handling
Try-with-resources is awesome!

Explanation:

  • Resources (FileWriter, Scanner) declared in parentheses after try
  • Automatically calls close() when try block ends
  • Works even if exception occurs - guaranteed cleanup
  • Cleaner, safer code - no need to manually close
  • This is the recommended way to handle file operations

File Handling Classes Comparison

1. FileWriter

Used for writing text data to files. Simple and straightforward for basic text writing operations.

Use for: Writing simple text files, logs, user data

2. BufferedWriter

Wraps FileWriter to write data more efficiently. Uses buffer to reduce disk operations. Better for large files.

Use for: Writing large amounts of text, better performance

3. FileReader

Reads characters from file one by one. Low-level reading, not very efficient for text files.

Use for: Basic character-by-character reading

4. BufferedReader

Reads text from file line by line efficiently using a buffer. Faster than FileReader for large files.

Use for: Reading large text files line by line

5. Scanner

Most convenient for reading files. Can parse different data types and read line by line easily.

Use for: Reading and parsing text files, easiest to use

6. FileInputStream / FileOutputStream

Used for reading/writing binary data (bytes). Perfect for images, audio, video, or any non-text files.

Use for: Binary files, images, media files

Complete File Handling Example

A practical example combining all file operations:

Example: Student Records Management

import java.io.*;
import java.util.Scanner;

public class Main {
    
    // Method to create and write student record
    static void addStudent(String name, int rollNo, double marks) {
        try (FileWriter writer = new FileWriter("students.txt", true)) {
            writer.write(rollNo + "," + name + "," + marks + "\n");
            System.out.println("✓ Student added: " + name);
        } catch (IOException e) {
            System.out.println("Error adding student: " + e.getMessage());
        }
    }
    
    // Method to read and display all students
    static void displayStudents() {
        try (Scanner reader = new Scanner(new File("students.txt"))) {
            System.out.println("\n=== Student Records ===");
            System.out.println("Roll No | Name | Marks");
            System.out.println("------------------------");
            
            while (reader.hasNextLine()) {
                String line = reader.nextLine();
                String[] data = line.split(",");
                System.out.println(data[0] + " | " + data[1] + " | " + data[2]);
            }
        } catch (FileNotFoundException e) {
            System.out.println("No records found!");
        }
    }
    
    public static void main(String[] args) {
        // Add students
        addStudent("Rahul Kumar", 101, 95.5);
        addStudent("Priya Sharma", 102, 88.0);
        addStudent("Amit Patel", 103, 92.5);
        
        // Display all students
        displayStudents();
    }
}
Output:
✓ Student added: Rahul Kumar
✓ Student added: Priya Sharma
✓ Student added: Amit Patel

=== Student Records ===
Roll No | Name | Marks
------------------------
101 | Rahul Kumar | 95.5
102 | Priya Sharma | 88.0
103 | Amit Patel | 92.5

Explanation:

  • addStudent() - Appends student record to file in CSV format
  • displayStudents() - Reads file and displays formatted data
  • split(",") - Splits CSV line into array
  • Try-with-resources ensures files are closed properly
  • Data persists across program runs - permanent storage!

Common File Handling Exceptions

  • FileNotFoundException: File doesn't exist when trying to read
  • IOException: General input/output error during file operations
  • SecurityException: No permission to access the file
  • FileAlreadyExistsException: File already exists when trying to create

💡 Pro Tip: Always use try-catch blocks for file operations. File operations are prone to errors - files might not exist, permissions might be denied, disk might be full!

Best Practices

  • Always close resources: Use try-with-resources or manually call close()
  • Handle exceptions: File operations can fail - always use try-catch
  • Check file existence: Use exists() before reading/deleting
  • Use absolute paths: Or clearly document where files should be located
  • Append vs Overwrite: Know when to use each mode
  • Validate file paths: Check for null or empty paths
  • Handle large files carefully: Use BufferedReader/Writer for efficiency
  • Close in finally block: If not using try-with-resources

🎯 Remember: Unclosed files waste system resources and might prevent other programs from accessing them. Always close your files!

Key Takeaways

  • File class: Create files, check existence, delete, get info
  • FileWriter: Write text to files (use append mode to add content)
  • Scanner: Easiest way to read files line by line
  • Try-with-resources: Automatically closes files - use it!
  • Always handle exceptions: File operations can fail
  • Close resources: Prevent resource leaks
  • Permanent storage: Files persist data beyond program execution

🚀 Next Steps: Practice by creating a simple diary app, todo list, or grade book that saves data to files. Real projects make the best practice!