🔰 Introduction
File Handling in Java lets you read/write files on disk. You can:
Read line by line using
BufferedReaderorScannerParse data using Scanner’s methods (nextLine(), nextInt(), etc.)
📘 Method 1: Reading a File using FileReader and BufferedReader
❔ What is FileReader?
FileReaderis a class in Java used to read character files.It reads the file character by character, making it suitable for text files.
But it's not efficient for large files since it reads one character at a time.
❔ What is BufferedReader?
BufferedReaderis a wrapper overFileReaderthat buffers the input for faster reading.It allows us to read the file line by line using
.readLine(), which is much faster than reading character by character.
✅ Why use both together?
Using them together:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));FileReaderhandles reading from the file.BufferedReaderimproves performance and provides useful methods like.readLine().
🧾 Java Program to Read a File
import java.io.*;
public class ReadFileExample {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("example.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
fr.close();
} catch (IOException e) {
System.out.println("File not found or error reading the file.");
e.printStackTrace();
}
}
}📄 Sample File: example.txt
Java is simple.
It is platform independent.
File handling is important.Java is simple.
It is platform independent.
File handling is important.🧾 Explanation of Code
Line of Code | What it Does |
|---|---|
FileReader fr = new FileReader(...) | Opens the file to read it character by character. |
BufferedReader br = new BufferedReader(fr) | Adds buffering and enables reading lines easily. |
br.readLine() | Reads the next line (until newline |
while ((line = br.readLine()) != null) | Loops through all lines in the file. |
System.out.println(line) | Prints each line on the console. |
br.close(); fr.close(); | Closes the file to release system resources. |
catch (IOException e) | Handles errors like file not found or read error. |
🔐 When to Use This Method?
Use Case | Use it? |
|---|---|
Reading small/medium text files | ✅ Yes |
Needing line-by-line reading | ✅ Yes |
Reading binary files | ❌ No |
Reading huge files efficiently | ✅ BufferedReader helps! |
📘 Method 2: Reading a File using Scanner
📦 What is Scanner?
The Scanner class (from the java.util package) is used to read input easily — from the console, files, or strings.
It parses primitive types like int, double, and also String, making it very versatile for both console input and file reading.
✅ Import Statement
Before using Scanner, you must import it:
import java.util.Scanner;📘 Use Case 1: Reading Input from Console
import java.util.Scanner;
public class ConsoleInputExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.println("Hello " + name + ", you are " + age + " years old.");
sc.close();
}
}🧪 Sample Input:
Enter your name: Alex
Enter your age: 22Hello Alex, you are 22 years old.📘 Use Case 2: Reading Input from a File using Scanner
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileScannerExample {
public static void main(String[] args) {
try {
File file = new File("example.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
e.printStackTrace();
}
}
}📄 Sample File: example.txt
Java is simple.
It is platform independent.
File handling is important.Java is simple.
It is platform independent.
File handling is important.🔧 Common Scanner Methods
Method | Description | Example Input | Output |
|---|---|---|---|
next() | Reads next word (until space) | Hello World | Hello |
nextLine() | Reads the entire line including spaces | Hello World | Hello World |
nextInt() | Reads an integer | 45 | 45 |
nextDouble() | Reads a decimal number | 3.14 | 3.14 |
hasNext() | Checks if more input is available | — | true/false |
hasNextLine() | Checks if another line is available in file | — | true/false |
close() | Closes the scanner | — | — |
printStackTrace() | It is used to display the full details of an exception, including the type, message, and the exact line in the code where it occurred. | — | — |
⚠️ Important Tips
After reading a number using
nextInt()ornextDouble(), usenextLine()to clear the leftover newline:int age = sc.nextInt(); sc.nextLine(); // Clear newlineAlways close the scanner after use to free resources:
sc.close();
📌 When to Use Scanner?
Task | Use Scanner? |
|---|---|
Reading user input | ✅ Yes |
Reading structured text files | ✅ Yes |
Reading huge files (line-by-line) | ❌ Better use BufferedReader |
Parsing tokens from strings | ✅ Yes |