Java File Handling – Read, Write, Delete, and Create Files
Introduction – Why File Handling is Crucial in Java
In any real-world application, storing and retrieving data from files is a critical operation — from logs and reports to user-generated content and configurations. Java provides robust tools to handle file operations such as reading, writing, creating, deleting, and modifying files, all under the java.io and java.nio.file packages.
In this guide, you’ll learn:
- How to work with files in Java
- File creation, reading, writing, and deletion
- Using
File,FileWriter,FileReader,BufferedReader, andFilesclass - Best practices for file handling and exception management
Java File Handling Packages
Java provides two primary packages for file operations:
| Package | Description |
|---|---|
java.io | Legacy file handling classes (File, FileReader) |
java.nio.file | Modern, more efficient API with Path, Files |
Creating a File in Java
Using File Class
import java.io.File;
import java.io.IOException;
public class CreateFile {
public static void main(String[] args) {
try {
File myFile = new File("example.txt");
if (myFile.createNewFile()) {
System.out.println("File created: " + myFile.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Explanation:
createNewFile()creates a new file if it doesn’t exist.- Handles
IOExceptionusingtry-catch.
Writing to a File in Java
Using FileWriter
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello, Java File Handling!");
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:
FileWriterwrites characters to a file.- Always close the writer using
close()to flush and free resources.
Tip: Use BufferedWriter for better performance on large data writes.
Reading from a File in Java
Using FileReader and BufferedReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:
BufferedReaderreads text efficiently line by line.readLine()returnsnullwhen the end of the file is reached.
Deleting a File in Java
import java.io.File;
public class DeleteFile {
public static void main(String[] args) {
File file = new File("example.txt");
if (file.delete()) {
System.out.println("Deleted the file: " + file.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
Explanation:
delete()returnstrueif file deletion is successful.
Modern File Handling – java.nio.file.Files
Creating and Writing in One Step
import java.nio.file.*;
import java.io.IOException;
import java.util.List;
public class ModernFileWrite {
public static void main(String[] args) throws IOException {
Path path = Paths.get("modern.txt");
Files.write(path, List.of("Line 1", "Line 2"), StandardOpenOption.CREATE);
}
}
Explanation:
Files.write()is more concise.- Supports multiple lines with
List.of().
Reading All Lines at Once
List<String> lines = Files.readAllLines(Paths.get("modern.txt"));
lines.forEach(System.out::println);
Note: Ideal for small to medium files.
Checking If a File Exists
Path path = Paths.get("modern.txt");
if (Files.exists(path)) {
System.out.println("File exists!");
}
Handling File Permissions and Properties
Getting File Info
File file = new File("example.txt");
System.out.println("File name: " + file.getName());
System.out.println("Absolute path: " + file.getAbsolutePath());
System.out.println("Writable: " + file.canWrite());
System.out.println("Readable: " + file.canRead());
System.out.println("File size in bytes: " + file.length());
Best Practices for File Handling
- Always close streams (
FileReader,FileWriter, etc.) - Use
try-with-resourcesto auto-close resources - Check file existence before reading/deleting
- Use
java.nio.filefor modern projects - Handle exceptions properly to avoid crashing apps
Summary – Mastering Java File Handling
Java provides a powerful and flexible set of APIs to handle file operations — essential for developing real-world applications that require data persistence, logging, or report generation. Whether you’re creating a log file, saving user data, or processing configuration files, Java’s file handling capabilities make it all possible.
Key Takeaways:
- Use
Fileclass for basic operations like creation, deletion, and info retrieval - Use
FileReader,FileWriter, andBufferedReaderfor traditional I/O - Prefer
java.nio.file.FilesandPathfor modern, cleaner file operations - Always handle exceptions and close file resources properly
- Apply
try-with-resourcesand null-safety checks for production-grade reliability
From basic file creation to stream-based file writing, this guide equips you with the tools and examples needed to confidently manage files in Java.
FAQs – Java File Handling
What is the difference between FileWriter and BufferedWriter?
BufferedWriter provides buffering for FileWriter, which improves write performance for large files.
Which package is preferred: java.io or java.nio.file?
java.nio.file is more modern, efficient, and recommended for new applications.
How can I read a file line-by-line?
Use BufferedReader.readLine() inside a loop until it returns null.
How to check if a file exists in Java?
Use new File("filename").exists() or Files.exists(Path).
How to write multiple lines to a file?
Use Files.write(Path, List<String>) or write manually using BufferedWriter.
Share Now :
