File Input Output Operations
File handling in Java is the process of creating, reading, writing, and modifying files stored on a computer using Java programs.
It allows a program to store data permanently instead of keeping it only in memory.
Definition
File handling is used to perform input and output (I/O) operations on files, such as:
Creating a file
Reading data from a file
Writing data to a file
Appending data to a file
Deleting a file
Common Classes Used
Java provides several classes in the [Link] package for file handling.
Some commonly used ones are:
o File – Represents a file or directory
o FileReader – Reads characters from a file
o FileWriter – Writes characters to a file
o BufferedReader – Reads text efficiently
o Scanner – Reads input from files
Simple Java Program to Write data into a File
import [Link];
import [Link];
public class FileExample {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("[Link]");
[Link]("Hello Java File Handling");
[Link]();
[Link]("File written successfully");
} catch(IOException e) {
[Link]("Error: " + e);
}
}
}
Explanation (Very Simple)
1. FileWriter is used to write data to a file.
2. "[Link]" is the file name created in the project folder.
3. write() writes the text to the file.
4. close() closes the file.
5. try-catch handles IOException.
Output
Console:
File written successfully
File [Link] will contain:
Hello Java File Handling
Key Points
File handling uses streams for input and output.
Files store permanent data.
Exception handling is usually required for file operations.
Simple Program to Read from a File
import [Link];
public class ReadFile {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("[Link]");
int i;
while((i = [Link]()) != -1)
{
[Link]((char)i);
}
[Link]();
}
}
Output
Hello Java File Handling
Simple Program to append data into an existing File
import [Link];
import [Link];
public class FileAppendDemo {
public static void main(String[] args) {
String dataToAppend = "This line will be appended to the file.\n";
FileWriter fw = null;
try {
// 1. Create FileWriter in append mode (true)
fw = new FileWriter("[Link]", true);
// 2. Write data to the file
[Link](dataToAppend);
[Link]("Data appended successfully!");
} catch (IOException e) {
// Handle file I/O errors
[Link]("Error: " + [Link]());
} finally {
// 3. Close the FileWriter to release resources
try {
if (fw != null) {
[Link]();
}
} catch (IOException e) {
[Link]();
}
}
}
}
Simple Program to Count Lines of an existing File
Java Program – Count Lines Using hasNextLine()
import [Link];
import [Link];
import [Link];
public class LineCountScannerDemo {
public static void main(String[] args) {
String filename = "[Link]";
int lineCount = 0;
Scanner sc = null; // Declare outside try
try {
// 1. Create File object
File file = new File(filename);
// 2. Create Scanner object
sc = new Scanner(file);
// 3. Count lines using hasNextLine()
while ([Link]()) {
[Link]();
lineCount++;
// 4. Print result
[Link]("Number of lines in the file: " + lineCount);
} catch (FileNotFoundException e) {
[Link]("File not found: " + [Link]());
} finally {
// 5. Cleanup resource
if (sc != null) {
[Link]();
[Link]("Scanner closed.");
}
}
Explanation
1️⃣ Create File Object
File file = new File(filename);
Represents the file to read.
2️⃣ Use Scanner
Scanner sc = new Scanner(file);
Reads file contents line by line.
3️⃣ Count Lines with hasNextLine()
while ([Link]()) {
[Link](); // Read line
lineCount++; // Increment counter
}
hasNextLine() checks if there’s another line to read.
nextLine() reads and moves to the next line.
4️⃣ Close Scanner
[Link]();
Frees file resources.
5️⃣ Print Result
[Link]("Number of lines in the file: " + lineCount);
Shows total lines in the file.
Sample Output
If [Link] contains:
Hello Java
This is line 2
This is line 3
Output:
Number of lines in the file: 3
✅ Key Points
hasNextLine() + nextLine() is simpler than BufferedReader for beginners.
Use try-catch for FileNotFoundException.
Always close the Scanner to release resources.
Exception handling is very important in file operations because working with files often involves situations that can fail
unexpectedly, and Java forces us to handle many of these errors.
Reasons why it is important:
1️⃣ Files may not exist
If your program tries to read a file that doesn’t exist, a FileNotFoundException occurs.
Example:
File file = new File("[Link]");
Scanner sc = new Scanner(file); // throws FileNotFoundException if file missing
Without exception handling, the program will crash.
2️⃣ Prevent program from crashing
If errors occur while reading/writing a file, try-catch blocks allow the program to handle the error gracefully instead of stopping
abruptly.
3️⃣ Resources need proper cleanup
File operations use system resources (streams).
Exception handling with a finally block ensures files and streams are properly closed, preventing resource leaks.
4️⃣ Handle unexpected errors
Writing to a file may fail due to:
o Lack of permission
o Disk full
o File being used by another program
Using try-catch lets your program handle these situations safely.
Example
import [Link].*;
import [Link];
public class FileReadDemo {
public static void main(String[] args) {
Scanner sc = null;
try {
File file = new File("[Link]");
sc = new Scanner(file);
while ([Link]()) {
[Link]([Link]());
}
} catch (FileNotFoundException e) {
[Link]("Error: File not found!");
} finally {
if (sc != null) [Link](); // ensures resource is closed
}
}
}
Even if the file is missing, the program does not crash.
Scanner is always closed, preventing resource leaks.
File Delete Operation
To delete a file in Java, you have a few common options depending on the Java version and API you want to use.
1. Using File class (works in older Java versions)
Use the Java File Class and its delete() method.
import [Link];
public class DeleteFileExample {
public static void main(String[] args) {
File file = new File("[Link]");
if ([Link]()) {
[Link]("File deleted successfully.");
} else {
[Link]("Failed to delete the file.");
}
}
}
Notes:
Returns true if deletion succeeded.
Returns false if the file doesn’t exist or deletion failed.
2. Using Files class (recommended for modern Java)
Using Java NIO Files Class with Java Path Interface.
import [Link];
import [Link];
public class DeleteFileExample {
public static void main(String[] args) {
try {
[Link]([Link]("[Link]"));
[Link]("File deleted successfully.");
} catch (Exception e) {
[Link]("Error deleting file: " + [Link]());
}
}
}
Advantages:
Throws clear exceptions (like NoSuchFileException)
Better error handling.
3. Delete only if file exists
[Link]([Link]("[Link]"));
This avoids exceptions if the file is missing.
✅ Summary
Method Package Behavior
[Link]() [Link] Simple, returns boolean
[Link]() [Link] Modern, throws exceptions
[Link]() [Link] Safe delete