File Handling ποΈ¶
Mentor's Note: Usually, when your program stops, all your data disappears (like a whiteboard being erased). File Handling is how you "Save your Work" to the hard drive so it stays there forever! π‘
π The Scenario: The Physical File Cabinet ποΈ¶
Imagine you are a secretary in a large office.
- The File Object (The Folder Label): Creating a
Fileobject is like Writing a label on a new folder. π·οΈ It doesn't mean the folder actually exists yet; it's just the idea of a folder named "test.txt." - Create (Making the Folder):
createNewFile()is like Actually putting a new folder in the cabinet. π - Write (Putting a Paper in):
FileWriteris like Writing on a piece of paper and placing it inside the folder. π - Read (Taking the Paper out):
Scanneris like Reading the paper line by line to see what's written. π - Delete (Shredding the Folder):
delete()is like Shredding the whole folder when you are done with it. ποΈ - The Result: You have a permanent record of everything your program did. β
π¨ Visual Logic: The File Lifecycle¶
graph TD
A[File Object: Label π·οΈ] --> B{Does it exist?}
B -- No --> C[createNewFile π]
B -- Yes --> D[FileWriter: Write π]
D --> E[Scanner: Read π]
E --> F[Delete: Trash ποΈ]
π Concept Explanation¶
1. The File Class ποΈ¶
The File class in java.io package allows us to work with files. Important: Creating a File object DOES NOT create a file on your disk yet!
2. Creating & Writing π¶
We use createNewFile() to make the file and FileWriter to "Talk" to it.
- Rule: Always Close your writer when done, or the data might not be saved! π
3. Reading π¶
The Scanner class is the easiest way to read text files line by line.
4. File Information π¶
You can ask the file questions like:
- exists(): Are you there?
- getName(): What is your name?
- getAbsolutePath(): Where exactly are you on the computer? π
- length(): How big are you (in bytes)? π
π» Implementation: The Office Lab¶
// π Scenario: Managing a text file
// π Action: Create, Write, and Read
import java.io.*; // Import all I/O tools
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
// π·οΈ Step 1: Label the folder
File myFile = new File("office_data.txt");
// π Step 2: Create the folder if it doesn't exist
if (myFile.createNewFile()) {
System.out.println("File created: " + myFile.getName());
}
// π Step 3: Write something inside
FileWriter writer = new FileWriter("office_data.txt");
writer.write("Hello from Java File Handling! π");
writer.close(); // Don't forget to close! π
// π Step 4: Read the content
Scanner reader = new Scanner(myFile);
while (reader.hasNextLine()) {
String data = reader.nextLine();
System.out.println("Reading: " + data);
}
reader.close();
} catch (IOException e) {
System.out.println("An error occurred. π«");
}
}
}
π Sample Dry Run (Execution)¶
| Step | Action | Logic | Computer's Action |
|---|---|---|---|
| 1 | new File() |
Labeling | Reserved a name in memory π·οΈ |
| 2 | createNewFile() |
Creation | Created a 0 KB file on disk π |
| 3 | writer.write() |
Processing | Buffering the text in memory π |
| 4 | writer.close() |
Closing | FLUSHING text to the disk π |
π Technical Analysis: Absolute vs Relative Paths π¶
- Relative Path:
office_data.txt(Look in the current project folder). ποΈ - Absolute Path:
C:\Users\Admin\Documents\office_data.txt(The full address from the start of the hard drive). πΊοΈ Pro Tip: Always use Relative paths in your code so it works on other people's computers too!
π― Practice Lab π§ͺ¶
Task: The Secret Diary
Task: Create a file named diary.txt. Write three lines about your day to it. Then, read it back and print it.
Goal: Master the FileWriter and Scanner flow. π‘
π‘ Interview Tip π¶
"Interviewers often ask: 'What happens if you don't close a FileWriter?' Answer: Data Loss. The text is stored in a temporary 'Buffer' and only written to the disk when you call
.close()or.flush(). If the program crashes before closing, the file might be empty!"
π‘ Pro Tip: "Always wrap your file handling in a
try-catchblock. The computer might be out of space, or the file might be read-onlyβthese are 'Exceptions' you must handle!" - Vishnu Damwala