File Handling in Java
⏱ Estimated reading time: 2 min
File handling in Java allows a program to read from and write to files, enabling data storage, retrieval, and manipulation outside the program. Java provides I/O streams and classes in java.io and java.nio packages for file operations.
1. Types of Files
-
Text Files → Contain human-readable characters.
-
Binary Files → Contain binary data like images, audio, or serialized objects.
2. Java File Handling Classes
Some commonly used classes for file handling:
| Class | Purpose |
|---|---|
File | Represents file or directory path |
FileReader | Reads data from a text file |
FileWriter | Writes data to a text file |
BufferedReader | Reads text efficiently (buffered) |
BufferedWriter | Writes text efficiently (buffered) |
PrintWriter | Writes formatted text |
FileInputStream | Reads bytes from a file (binary) |
FileOutputStream | Writes bytes to a file (binary) |
3. Creating a File
4. Writing to a File
5. Reading from a File
6. File Operations
-
Checking existence:
file.exists() -
Getting file info:
file.length(),file.getName(),file.getPath() -
Deleting a file:
file.delete() -
Creating directories:
file.mkdir()orfile.mkdirs()
7. Advantages of File Handling
-
Persistent storage of data.
-
Data sharing between programs.
-
Supports large data processing.
-
Enables backup and recovery of information.
8. Conclusion
File handling in Java provides a robust mechanism to read, write, and manage files. By using classes from java.io and java.nio packages, developers can handle both text and binary files efficiently, making applications data-persistent and versatile.
Register Now
Share this Post
← Back to Tutorials