File Handling in JAVA


Hello Java Learners! 👋
“File Handling feels scary or confusing?”
Not anymore! Let’s make it super simple and fun. ✨
Instead of diving into boring long theories (which you’ll find everywhere), here’s a blog that’ll help you grasp the real concept—because once you get the idea, the code becomes a breeze!
Table of Contents
What is File Handling?
Quick Look: File Operations
Java File Handling Classes & Methods
Let’s Start Playing with Files!
i. Creating a File
ii. Writing to a File
iii. Appending to a File
iv. Reading a File (3 Cool Ways!)
v. Deleting a File
Try-catch
Summary Table
# What is File Handling?
File handling means telling Java:
“Hey, open this file, write something cool in it, or read it later. Also, throw it away if it’s useless.”
We use classes like File, FileWriter, Scanner, BufferedReader, etc., to do this.
# Quick Look: File Operations
Task | Class | Notes |
Create | File | .createNewFile() |
Write | FileWriter | Overwrites content |
Append | FileWriter | Use true flag |
Read | Scanner | Line by line |
Read | FileReader | Char by char |
Read | BufferedReader | Super fast |
Delete | File | .delete() |
# Java File Handling Classes and Methods
File Class
Purpose: Used to create, check, delete, or get details about files and directories.
Key Methods:
createNewFile() : Creates a new file if it doesn’t exist.
delete() : Deletes a file or directory.
exists() : Checks if the file exists.
getName() , getAbsolutePath(), etc.: To get file details.
FileWriter Class
Purpose: Used to write character data to a file (overwrites by default).
Key Constructors:
FileWriter(String fileName) : Creates writer to write (overwrites).
FileWriter(String filename, true): Appends to file if true is passed.
Key Methods:
write(String): Writes the given text.
close(): Closes the writer to save changes.
Scanner Class
Purpose: Reads files easily, especially line by line.
Key Constructor:
- Scanner(File) : Reads the file.
Key Methods:
hasNextLine(): Checks if there’s another line.
nextLine(): Reads the next line.
FileReader Class
Purpose: Reads file character by character (low-level).
Key Method:
read(): Reads one character at a time and returns ASCII code (int).
close(): Closes the reader.
BufferedReader Class
Purpose: Reads files line by line efficiently (faster than Scanner).
Key Constructor:
- BufferedReader(new FileReader("filename")): Combines both.
Key Method:
readLine(): Reads an entire line.
close(): Closes the reader.
# Let’s Start Playing with Files!
i. Creating a File
import java.io.File;
File file = new File("data.txt"); // Creating File object for "data.txt"
file.createNewFile(); // Actually creates the file (if it doesn’t exist)
📓Think of it like creating a new notebook .
ii. Writing to a File
import java.io.FileWriter;
FileWriter fw = new FileWriter("data.txt");// Create a FileWriter to write to the file
fw.write("Hello World!");// Write a string to the file
fw.close();// Always close the file after writing
📝 Writes over old content like using a pen on fresh page.
iii. Appending to a File
import java.io.FileWriter;
FileWriter fw = new FileWriter("data.txt", true);// true enables append mode
fw.write("\nMore lines!");//Adds new text without deleting existing data
fw.close();// Close the file to save changes
📌 Adds new stuff at the bottom like sticking notes.
iv. Reading a File (3 Cool Ways!)
a. Using Scanner (Line-by-Line)
import java.util.Scanner;
import java.io.File;
Scanner sc = new Scanner(new File("data.txt"));// Scanner to read the file
while (sc.hasNextLine()) // Loop until no more lines
System.out.println(sc.nextLine());// Print each line one by one
sc.close();// Close the scanner
🔍 Best for casual reading, like reading a diary.
b. Using FileReader (Char-by-Char)
import java.io.FileReader;
FileReader fr = new FileReader("data.txt");// Create FileReader
int ch;// To store characters read
while((ch = fr.read()) != -1) // Read one character at a time
System.out.print((char) ch);// Print the character
fr.close(); // Close the reader
🔠 Like reading alphabet soup letter by letter!
c. Using BufferedReader (Fast & Smooth)
import java.io.BufferedReader;
import java.io.FileReader;
BufferedReader br = new BufferedReader(new FileReader("data.txt"));// Chain FileReader to BufferedReader
String line;// Stores each line
while((line = br.readLine()) != null) // Read until end
System.out.println(line);// Print each line
br.close();// Close reader
🚀 Efficient and fast — perfect for big files!
v. Deleting a File
import java.io.File;
File f = new File("data.txt");// Reference to the file
f.delete(); // Deletes file (returns true if successful)
🗑️ Like throwing away an old paper.
# Try-catch
Sometimes, things go wrong... maybe the file doesn't exist, or there's a typo in the filename. Java doesn’t like surprises, so it wants you to handle errors gracefully using a try-catch block!
Think of try as:
👉 “Let me try this risky task...”
And catch as:
👉 “If something breaks, I’ll catch the error and handle it nicely.”
import java.io.*; // Importing all necessary classes from java.io package
public class Main {
public static void main(String[] args) {
try {
// Creating a FileReader to read from "data.txt"
FileReader fr = new FileReader("data.txt");
int ch; // Variable to hold each character (as int)
// Read each character until end of file (-1)
while ((ch = fr.read()) != -1)
System.out.print((char) ch); // Convert int to char and print it
fr.close(); // Close the FileReader to free system resources
} catch (IOException e) {
// If there's any error (e.g., file not found), print the error message
System.out.println("Error: " + e);
}
}
}
Summary Table
Action | Code Signatures |
Create | new File().createNewFile() |
Write | new FileWriter().write() |
Append | new FileWriter(file, true).write() |
Read (easy) | Scanner.nextLine() |
Read (char) | FileReader.read() |
Read (fast) | BufferedReader.readLine() |
Delete | File.delete() |
Ready to Conquer File Handling?
Now you can teach someone else! Because when file handling becomes fun, you don’t skip it—you enjoy it! 😄
Subscribe to my newsletter
Read articles from Tripti Bhatnagar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
