π 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 :
