๐ 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
, andFiles
class - 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
IOException
usingtry-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:
FileWriter
writes 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:
BufferedReader
reads text efficiently line by line.readLine()
returnsnull
when 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()
returnstrue
if 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-resources
to auto-close resources - โ Check file existence before reading/deleting
- โ
Use
java.nio.file
for 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
File
class for basic operations like creation, deletion, and info retrieval - โ
Use
FileReader
,FileWriter
, andBufferedReader
for traditional I/O - โ
Prefer
java.nio.file.Files
andPath
for modern, cleaner file operations - โ Always handle exceptions and close file resources properly
- โ
Apply
try-with-resources
and 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 :