File Handling in Java refers to the process of creating, reading, writing, and deleting files using Java programs. It allows applications to store and retrieve data permanently from the file system instead of keeping it only in memory.
🔹 Why File Handling is Important?
In real-world applications, data must be saved for future use. File handling helps in:
✔ Storing user data
✔ Reading configuration files
✔ Writing logs
✔ Processing large datasets
🔹 Java Packages for File Handling
Java provides built-in support through:
-
java.io(Input/Output streams) -
java.nio.file(New I/O – more efficient and modern)
🔹 1. Creating a File
java id="5ajxb4"
import java.io.File;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
File file = new File("example.txt");
if (file.createNewFile()) {
System.out.println("File created");
} else {
System.out.println("File already exists");
}
}
}
🔹 2. Writing to a File
```java id="40v5yg"
import java.io.FileWriter;
import java.io.IOException;
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello Java File Handling");
writer.close();
🔹 3. Reading from a File
java id="yh8e6y"
import java.io.File;
import java.util.Scanner;
File file = new File("example.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
sc.close();
🔹 4. Deleting a File
java id="vrg8ym"
File file = new File("example.txt");
if (file.delete()) {
System.out.println("File deleted");
}
🔹 Important Classes in File Handling
| Class | Purpose |
|---|---|
File |
Represents file/directory |
FileWriter |
Writes data to file |
FileReader |
Reads data from file |
BufferedReader |
Efficient reading |
BufferedWriter |
Efficient writing |
Scanner |
Reads data easily |
🔹 Character vs Byte Streams
Byte Streams →
FileInputStream,FileOutputStream
👉 Used for binary data (images, videos)Character Streams →
FileReader,FileWriter
👉 Used for text data
🔹 Modern Approach (NIO)
java id="fgk2bm"
import java.nio.file.*;
Files.write(Paths.get("example.txt"), "Hello NIO".getBytes());
👉 Faster and more flexible than traditional I/O.
🔹 Real-Time Use Cases
- Saving user details in applications
- Reading CSV/Excel files
- Writing logs in enterprise apps
- Uploading/downloading files
🚀 Final Thoughts
File Handling in Java is essential for building real-world applications where data persistence is required. Understanding both traditional I/O and modern NIO APIs will make you a strong Java developer.
If you want to learn Core Java concepts like File Handling with real-time examples and projects, check out:
👉 No 1 Core JAVA Online Training in Hyderabad
Top comments (0)