Java File Handling โ Read, Write, Create & Delete Files with Ease (2025)
Introduction โ Why Learn Java File Handling?
In real-world applications, reading and writing files is a core requirementโwhether it’s saving user data, logs, configuration, or reports. Javaโs java.io and java.nio packages provide robust tools to manage file operations.
In this guide, youโll learn:
- How to create and write to files
- How to read content from files
- How to delete files using Java
- Best practices for file handling
Topics Covered
| Topic | Description |
|---|---|
| Java Files | Introduction to file management in Java |
| Java Create/Write Files | Creating and writing text into files |
| Java Read Files | Reading content line-by-line |
| Java Delete Files | Deleting existing files using File.delete() |
Java Files โ File Class Overview
Java provides the File class (from java.io) to represent file and directory pathnames.
Example: Checking if a file exists
import java.io.File;
public class FileCheck {
public static void main(String[] args) {
File file = new File("example.txt");
if (file.exists()) {
System.out.println("File exists.");
} else {
System.out.println("File does not exist.");
}
}
}
Line-by-Line Explanation:
File file = new File(...)โ Represents a file or pathfile.exists()โ Checks if the file physically exists
Java Create/Write Files โ FileWriter
You can use FileWriter or BufferedWriter to create and write to files.
Example:
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("output.txt");
writer.write("Welcome to Java File Handling!");
writer.close();
System.out.println("Successfully written to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
}
}
}
Line-by-Line Explanation:
FileWriter writer = new FileWriter(...)โ Creates or opens the filewriter.write(...)โ Writes contentwriter.close()โ Closes the file (important for saving data)
Java Read Files โ FileReader/BufferedReader
Java supports reading files using FileReader, BufferedReader, or Scanner.
Example (BufferedReader):
import java.io.*;
public class ReadFile {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("output.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
System.out.println("Unable to read file.");
}
}
}
Line-by-Line Explanation:
BufferedReader+FileReaderโ Opens file for readingreadLine()โ Reads each line until the end (null)reader.close()โ Frees up system resources
Java Delete Files โ File.delete()
Use the delete() method to remove a file.
Example:
import java.io.File;
public class DeleteFile {
public static void main(String[] args) {
File file = new File("output.txt");
if (file.delete()) {
System.out.println("Deleted: " + file.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
Line-by-Line Explanation:
file.delete()โ Attempts to delete the specified file- Returns
trueif successful,falseotherwise
Summary โ Recap & Next Steps
File handling in Java is essential for applications involving persistent storage, reporting, and configuration.
Key Takeaways:
- Use
File,FileWriter, andBufferedReaderfor file manipulation - Always close streams to avoid memory leaks
- Always handle exceptions using try-catch blocks
File.delete()allows cleanup of unneeded files
Whatโs Next?
- Learn about serialization for writing objects to files
- Use java.nio.file.Files for advanced file operations
- Try writing a log system or file-based database
Frequently Asked Questions (FAQs)
What is the difference between FileWriter and BufferedWriter?
FileWriter writes directly, while BufferedWriter buffers content before writing, improving performance for large files.
Can I append data to a file instead of overwriting?
Yes! Use new FileWriter("file.txt", true) to enable append mode.
What happens if the file doesnโt exist when reading?
Java throws a FileNotFoundException, which must be handled using try-catch.
Is it necessary to close the file after writing?
Absolutely. Not closing the file may result in unsaved data or resource leaks.
Can I delete a directory using File.delete()?
Only if the directory is empty. Use Files.delete(Path) for more advanced deletion.
Share Now :
