Open, close and use a file for reading and writing
📚 What is a File?
A file is like a notebook that lives on your computer. It stores data that your program can read or write. Think of it as a book you can open, read pages from, add new pages to, and then close when you're done.
🔓 Opening a File in Java
In Java, you open a file with a FileInputStream (for reading) or a FileOutputStream (for writing). The open() step is like flipping the cover of your notebook.
try {
FileInputStream fis = new FileInputStream("data.txt"); // Open for reading
FileOutputStream fos = new FileOutputStream("data.txt"); // Open for writing
} catch (FileNotFoundException e) {
e.printStackTrace();
}
⚠️ Common Mistake
Never forget to check if the file exists before opening it for reading. If it doesn't, Java throws a FileNotFoundException.
📖 Reading from a File
Once the file is open, you can read its contents byte by byte or line by line. Think of it as flipping through the pages of your notebook.
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // Process each line
}
✏️ Writing to a File
Writing is like writing a new page in your notebook. You can append to the end or overwrite the whole file.
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write("Hello, world!"); // Write a line
writer.newLine(); // Move to next line
writer.close(); // Don't forget to close!
🔒 Closing a File
Closing a file frees up system resources, just like closing a book lets you put it back on the shelf. In Java, you call close() on the stream.
reader.close(); // Close the reader writer.close(); // Close the writer
💡 Tip: Use try-with-resources
Java’s try-with-resources automatically closes streams, reducing the chance of leaks.
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
📊 File Operations Table
| Operation | Java Class | Typical Use |
|---|---|---|
| Open for reading | FileInputStream / FileReader |
Read existing data |
| Open for writing | FileOutputStream / FileWriter |
Create or overwrite data |
| Append to file | FileOutputStream (with true flag) |
Add new data at the end |
| Close stream | close() |
Release resources |
📝 Examination Tips
- Remember the order: Open → Read/Write → Close.
- Use
try-with-resources: It’s the safest way to ensure streams are closed. - Check for
FileNotFoundException: It’s a common error when the file path is wrong. - Explain the difference between
FileInputStreamandFileReader: The former reads raw bytes; the latter reads characters. - Show a small code snippet: Demonstrating opening, reading a line, and closing.
🤔 Quick Quiz
- What method do you call to release the file resource?
- Which Java class would you use to append data to an existing file?
- Why is
try-with-resourcespreferred over a plaintry/catch?
Revision
Log in to practice.