What is File Handling?
File handling in Java is the process of creating, reading, writing, and modifying files using Java programs.
For example, imagine we have employee details stored in a text file. Instead of manually entering employee details into our program, we can read the data directly from that file.
Let's understand how to read a file using a simple Employee Management System.
Employee Data (empData.txt)
First, let's create a text file containing employee details.
id,name,dept,salary
1,Subash,IT,25000
2,Ram,HR,30000
3,John,Testing,28000
Complete Code
Let's look at the complete controller code.
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileNotFoundException;
public class EmployeeController {
public static void main(String[] args) {
EmployeeService service = new EmployeeService();
File note = new File("empData.txt");
try {
FileReader reader = new FileReader(note);
BufferedReader br = new BufferedReader(reader);
String line = br.readLine();
line = br.readLine();
while (line != null) {
String[] words = line.split(",");
int id = Integer.parseInt(words[0].trim());
String name = words[1];
String dept = words[2];
int salary = Integer.parseInt(words[3].trim());
EmployeeEntity employee =
new EmployeeEntity(id, name, dept, salary);
service.addEmployee(employee);
line = br.readLine();
}
br.close();
} catch (FileNotFoundException fnf) {
System.out.println("File not found");
} catch (IOException io) {
System.out.println("IO exception");
}
service.viewEmployee();
}
}
Understanding the Code Bit by Bit
1. Creating a File Object
File note = new File("empData.txt");
First, we create a File object and pass the file path.
Here, the File class represents the file location. It doesn't read the file contents by itself.
2. Using FileReader
FileReader reader = new FileReader(note);
FileReader is used to read characters from the file.
We pass the File object to the FileReader constructor so it knows which file to read.
3. Using BufferedReader
BufferedReader br = new BufferedReader(reader);
BufferedReader takes the FileReader object as an argument.
It helps us read the file efficiently and provides a method called readLine() to read one line at a time.
4. Reading the File
String line = br.readLine();
line = br.readLine();
The first readLine() reads the header (id, name, dept, salary).
We call it again because we want to start reading the actual employee details, skipping the header.
5. Using While Loop
while (line != null) {
// Reading employee details
line = br.readLine();
}
The while loop continues as long as the line is not null.
When there are no more lines to read, readLine() returns null, and the loop stops.
6. Splitting the Data
String[] words = line.split(",");
Our employee details are separated by commas.
The split(",") method separates the values and stores them in a String array.
For example:
1,Subash,IT,25000
After splitting:
- words[0] = 1
- words[1] = Subash
- words[2] = IT
- words[3] = 25000
7. Converting String into Integer
int id = Integer.parseInt(words[0].trim());
int salary = Integer.parseInt(words[3].trim());
By default, the values we read from the file are Strings.
But our EmployeeEntity class expects ID and salary as integers.
So, we use Integer.parseInt() to convert String values into integers.
The trim() method removes unwanted spaces from the beginning and end of a String.
8. Creating an Employee Object
EmployeeEntity employee =
new EmployeeEntity(id, name, dept, salary);
Now that we have separated the employee details, we create an EmployeeEntity object using its constructor.
9. Adding Employee to ArrayList
service.addEmployee(employee);
We pass the Employee object to the service class.
The service class adds that object to the ArrayList.
This process repeats for every employee in the text file.
10. Closing the Reader
br.close();
Once reading is completed, we close the BufferedReader to release the resources associated with it.
11. Displaying Employees
service.viewEmployee();
Finally, we call the viewEmployee() method from our service class.
It displays all the employee objects stored in the ArrayList.
Java internally calls the toString() method of each EmployeeEntity object to display its details.
Exception Handling
While working with files, exceptions can occur.
For example:
-
FileNotFoundException: Occurs when the specified file cannot be found. -
IOException: Occurs when an input/output error happens while reading the file.
We handle these exceptions using try-catch blocks.
Conclusion
File handling makes it easier to read and store data using files.
In our Employee Management System, we used File, FileReader, and BufferedReader to read employee details from a text file, convert them into Employee objects, and store them in an ArrayList.
That's how we can use file handling in a simple Java application.
Top comments (0)