File Handling in Java is the process of creating, reading, writing, updating, and deleting files using Java programs. It enables applications to store data permanently instead of keeping it only in memory. Java File Handling practice questions with solutions help to understand the concepts.
For example:
- Saving student records
- Generating invoices
- Writing log files
- Reading configuration files
- Exporting reports
- Managing employee data
Without file handling, data stored in variables is lost when the program terminates.
Why Do We Need File Handling?
File handling helps developers:
- Store data permanently
- Read existing data
- Write new information
- Update records
- Delete unwanted files
- Build real-world desktop and enterprise applications
Java File Handling Classes
Java provides several classes for file operations.
Some of the most commonly used are:
FileFileReaderFileWriterBufferedReaderBufferedWriterPrintWriterScanner
Common File Operations
Java supports the following operations:
- Create File
- Read File
- Write File
- Append Data
- Delete File
- Rename File
- Check File Properties
The File Class
The File class belongs to the java.io package.
Example:
import java.io.File;
File file = new File("student.txt");
The File class itself does not read or write data.
It only represents the file or directory.
Real-World Applications of File Handling
File handling is widely used in:
- Banking Systems
- Hospital Management Systems
- School Management Software
- Inventory Management
- Payroll Systems
- Android Applications
- Spring Boot Applications
- Desktop Applications
Before Learning This Chapter
You should already understand:
- Variables
- Classes
- Objects
- Methods
- Exception Handling
Since file operations may generate exceptions, knowledge of Exception Handling is essential before learning file handling.
1. Java Program to Create a File
Problem Statement
Write a Java program to create a new file.
Java Solution
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
File file = new File("student.txt");
if (file.createNewFile()) {
System.out.println("File Created Successfully");
}
else {
System.out.println("File Already Exists");
}
}
catch (IOException exception) {
System.out.println(exception);
}
}
}
Sample Output
File Created Successfully
Explanation
The createNewFile() method creates a new file if it does not already exist.
If the file already exists, it returns false.
Concepts Covered
- File Class
- createNewFile()
- IOException
- File Creation
2. Java Program to Write Data into a File
Problem Statement
Write a Java program to write data into a file.
Java Solution
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("student.txt");
writer.write("Welcome to Java File Handling");
writer.close();
System.out.println("Data Written Successfully");
}
catch (IOException exception) {
System.out.println(exception);
}
}
}
Sample Output
Data Written Successfully
Explanation
FileWriter is used to write data into a file.
The close() method is important because it saves the data and releases system resources.
Concepts Covered
- FileWriter
- write()
- close()
- IOException
3. Java Program to Read Data from a File
Problem Statement
Write a Java program to read data from a file.
Java Solution
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
File file = new File("student.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
}
}
Sample Output
Welcome to Java File Handling
Explanation
The Scanner class reads the file line by line.
The loop continues until all lines have been read.
Finally, the scanner is closed to release resources.
Concepts Covered
- Scanner
- File Reading
- FileNotFoundException
- while Loop
4. Java Program to Append Data to a File
Problem Statement
Write a Java program to append new data to an existing file without deleting the old data.
Java Solution
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("student.txt", true);
writer.write("\nJava File Handling Practice Questions");
writer.close();
System.out.println("Data Appended Successfully");
}
catch (IOException exception) {
System.out.println(exception);
}
}
}
Sample Output
Data Appended Successfully
Explanation
Normally, FileWriter overwrites the existing file.
By passing true as the second argument:
FileWriter writer = new FileWriter("student.txt", true);
Java opens the file in append mode, preserving the existing content and adding the new data at the end.
Concepts Covered
- FileWriter
- Append Mode
- File Handling
- IOException
5. Java Program to Delete a File
Problem Statement
Write a Java program to delete a file from the system.
Java Solution
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("student.txt");
if (file.delete()) {
System.out.println("File Deleted Successfully");
}
else {
System.out.println("File Does Not Exist");
}
}
}
Sample Output
File Deleted Successfully
Explanation
The delete() method removes the file from the file system.
It returns:
true→ if the file is deleted successfully.false→ if the file does not exist or cannot be deleted.
Concepts Covered
- File Class
- delete()
- File Deletion
- Boolean Return Value
6. Java Program to Display File Information
Problem Statement
Write a Java program to display information about a file such as its name, path, size, and read/write permissions.
Java Solution
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("student.txt");
if (file.exists()) {
System.out.println("File Name : " + file.getName());
System.out.println("File Path : " + file.getAbsolutePath());
System.out.println("File Size : " + file.length() + " bytes");
System.out.println("Readable : " + file.canRead());
System.out.println("Writable : " + file.canWrite());
}
else {
System.out.println("File Does Not Exist");
}
}
}
Sample Output
File Name : student.txt
File Path : C:\Java\student.txt
File Size : 65 bytes
Readable : true
Writable : true
Explanation
The File class provides several useful methods:
getName()→ Returns the file name.getAbsolutePath()→ Returns the complete file path.length()→ Returns the file size in bytes.canRead()→ Checks if the file is readable.canWrite()→ Checks if the file is writable.
Concepts Covered
- File Class
- File Information
- File Properties
- File Methods
7. Java Program to Rename a File
Problem Statement
Write a Java program to rename an existing file.
Java Solution
import java.io.File;
public class Main {
public static void main(String[] args) {
File oldFile = new File("student.txt");
File newFile = new File("students.txt");
if (oldFile.renameTo(newFile)) {
System.out.println("File Renamed Successfully");
}
else {
System.out.println("Unable to Rename File");
}
}
}
Sample Output
File Renamed Successfully
Explanation
The renameTo() method changes the name of an existing file.
It returns:
true→ Rename successful.false→ Rename failed.
Concepts Covered
- File Class
- renameTo()
- File Rename
- File Operations
8. Java Program to Check Whether a File Exists
Problem Statement
Write a Java program to check whether a file exists.
Java Solution
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("student.txt");
if (file.exists()) {
System.out.println("File Exists");
}
else {
System.out.println("File Not Found");
}
}
}
Sample Output
File Exists
Explanation
The exists() method checks whether the specified file or directory is available.
It returns:
true→ File exists.false→ File does not exist.
Concepts Covered
- exists()
- File Checking
- File Class
- File Operations
9. Java Program to Read a File Using BufferedReader
Problem Statement
Write a Java program to read data from a file using BufferedReader.
Java Solution
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("student.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
catch (IOException exception) {
System.out.println(exception);
}
}
}
Sample Output
Welcome to Java File Handling
Java Practice Questions
Explanation
BufferedReader reads text efficiently by buffering characters.
The readLine() method reads one line at a time until the end of the file.
Concepts Covered
- BufferedReader
- FileReader
- readLine()
- File Reading
10. Java Program to Write Data Using BufferedWriter
Problem Statement
Write a Java program to write data into a file using BufferedWriter.
Java Solution
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("student.txt"));
writer.write("Java BufferedWriter Example");
writer.newLine();
writer.write("Learning Java File Handling");
writer.close();
System.out.println("Data Written Successfully");
}
catch (IOException exception) {
System.out.println(exception);
}
}
}
Sample Output
Data Written Successfully
Explanation
BufferedWriter improves writing performance by storing characters in a buffer before writing them to the file.
Useful methods:
write()→ Writes text.newLine()→ Inserts a new line.close()→ Saves data and releases resources.
Concepts Covered
- BufferedWriter
- FileWriter
- write()
- newLine()
- File Writing
11. Java Program to Copy One File to Another
Problem Statement
Write a Java program to copy the contents of one file into another file.
Java Solution
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("student.txt");
FileWriter writer = new FileWriter("backup.txt");
int character;
while ((character = reader.read()) != -1) {
writer.write(character);
}
reader.close();
writer.close();
System.out.println("File Copied Successfully");
}
catch (IOException exception) {
System.out.println(exception);
}
}
}
Sample Output
File Copied Successfully
Explanation
The program reads one character at a time from the source file and writes it into the destination file until the end of the file is reached.
Concepts Covered
- FileReader
- FileWriter
- File Copy
- Character Stream
12. Java Program to Count the Number of Lines in a File
Problem Statement
Write a Java program to count the total number of lines present in a file.
Java Solution
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
int lines = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader("student.txt"));
while (reader.readLine() != null) {
lines++;
}
reader.close();
System.out.println("Total Lines : " + lines);
}
catch (IOException exception) {
System.out.println(exception);
}
}
}
Sample Output
Total Lines : 5
Explanation
The program reads the file line by line.
Each successful call to readLine() increments the line counter.
When readLine() returns null, the end of the file has been reached.
Concepts Covered
- BufferedReader
- readLine()
- Line Counting
- File Reading
13. Java Program to Count Words in a File
Problem Statement
Write a Java program to count the total number of words in a file.
Java Solution
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
int words = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader("student.txt"));
String line;
while ((line = reader.readLine()) != null) {
String[] wordArray = line.trim().split("\\s+");
words += wordArray.length;
}
reader.close();
System.out.println("Total Words : " + words);
}
catch (IOException exception) {
System.out.println(exception);
}
}
}
Sample Output
Total Words : 18
Explanation
Each line is split using whitespace (\\s+).
The length of the resulting array gives the number of words in that line.
The counts are added together to obtain the total number of words in the file.
Concepts Covered
- BufferedReader
- String Split
- Word Counting
- File Processing
14. Java Program to Read a File Character by Character
Problem Statement
Write a Java program to read a file character by character.
Java Solution
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("student.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
}
catch (IOException exception) {
System.out.println(exception);
}
}
}
Sample Output
Welcome to Java File Handling
Learning File Operations
Explanation
The read() method returns one character at a time.
When the end of the file is reached, it returns -1.
Each integer value is converted into a character using type casting.
Concepts Covered
- FileReader
- Character Reading
- read()
- File Handling
15. Java Program to Create a Real-World Student Record File System
Problem Statement
Write a Java program to store student information in a file.
Java Solution
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("students.txt");
writer.write("ID : 101\n");
writer.write("Name : Rahul Sharma\n");
writer.write("Course : Java Programming\n");
writer.write("City : Delhi\n");
writer.close();
System.out.println("Student Record Saved Successfully");
}
catch (IOException exception) {
System.out.println(exception);
}
}
}
Sample Output
Student Record Saved Successfully
Explanation
The program stores structured student information in a text file.
This technique is commonly used in:
- School Management Systems
- College Management Software
- Student Information Systems
- Desktop CRUD Applications
In real-world applications, the data is generally stored in databases, but text files are useful for learning file handling concepts.
Concepts Covered
- FileWriter
- Student Record System
- Data Storage
- File Operations
Chapter Summary
In this chapter, you learned Java File Handling, an essential concept used to store, retrieve, update, and manage data in files. File handling allows Java applications to work with permanent storage instead of keeping information only in memory.
You explored how to create files, write data, read file contents, append new information, delete files, and retrieve file details. You also learned how to use buffered streams for efficient file operations and practiced real-world file management examples.
Throughout this chapter, you covered:
- File Class
- Creating Files
- Reading Files
- Writing Files
- Appending Data
- Deleting Files
- Renaming Files
- Displaying File Information
- BufferedReader
- BufferedWriter
- Copying Files
- Counting Lines
- Counting Words
- Reading Character by Character
- Student Record Management Example
These concepts are widely used in desktop applications, enterprise software, Spring Boot projects, Android applications, and data processing systems.
Key Takeaways
- The
Fileclass represents files and directories. FileWriteris used to write data into files.FileReaderis used to read file contents.BufferedReaderimproves file reading performance.BufferedWriterimproves file writing performance.- Append mode allows adding data without overwriting existing content.
- Java provides methods to rename and delete files.
- File information such as name, size, and path can be retrieved easily.
- Properly closing files prevents memory leaks and resource issues.
- File handling is one of the core skills required for Java developers.
Frequently Asked Questions (FAQs)
1. What is File Handling in Java?
File Handling is the process of creating, reading, writing, updating, and deleting files using Java programs.
2. Which package is used for File Handling?
Most file handling classes belong to the following package:
import java.io.*;
3. What is the purpose of the File class?
The File class represents a file or directory.
It provides methods to:
- Create files
- Delete files
- Rename files
- Check file existence
- Retrieve file information
4. What is the difference between FileReader and BufferedReader?
| FileReader | BufferedReader |
|---|---|
| Reads one character at a time | Reads data using a buffer |
| Slower | Faster |
| Used for small files | Recommended for large files |
5. What is the difference between FileWriter and BufferedWriter?
| FileWriter | BufferedWriter |
|---|---|
| Writes directly to the file | Uses an internal buffer |
| Slower | Faster |
| Suitable for simple tasks | Better for large data writing |
6. How can you append data to a file?
Append mode is enabled by passing true to the FileWriter constructor.
Example:
FileWriter writer = new FileWriter("student.txt", true);
This preserves the existing data and adds new content at the end of the file.
7. Why should files be closed after use?
Closing a file:
- Saves pending data.
- Releases system resources.
- Prevents memory leaks.
- Avoids file corruption.
Example:
reader.close();
writer.close();
8. Where is Java File Handling used in real-world applications?
Java File Handling is commonly used in:
- Student Management Systems
- Banking Applications
- Hospital Management Software
- Inventory Systems
- Payroll Applications
- Log File Generation
- Report Export Systems
- Spring Boot Projects
- Android Applications
- Desktop Software
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
