1 Opening a File with the File Class
The teacher demonstrated how to access a text file in Java.
"First," they said, "we create a File object that points to where our file is stored."
The File class in Java represents a file or directory path. It doesn't actually contain the file's data - it's like a pointer or handle to the file's location.
Creating a File object does NOT create the actual file on disk! It simply creates a Java object that represents the file path. The file may or may not exist.
2 Absolute vs Relative Paths
When specifying a file location, you have two options:
Complete location from the root of the file system.
Location relative to your project folder.
If you use "C:/Users/Ahmed/Documents/data.txt" and then share your code with a friend, it won't work on their computer because they don't have the same folder structure!
Relative paths are portable - they work on any computer as long as the project folder structure remains the same. Always prefer relative paths!
3 Checking If a File Exists
Before reading from a file, it's a good practice to check if it actually exists:
The teacher explained, "Think of it like how Windows Explorer checks files on your computer. The File class lets us do similar things - explore file properties, check if they exist, see their size, and more."
4 Useful File Class Methods
The File class provides many helpful methods:
| Method | Returns | Description |
|---|---|---|
exists() |
boolean | Returns true if file/folder exists |
canRead() |
boolean | Returns true if file is readable |
canWrite() |
boolean | Returns true if file is writable |
isDirectory() |
boolean | Returns true if it's a folder |
isFile() |
boolean | Returns true if it's a file |
getName() |
String | Returns the file name |
getAbsolutePath() |
String | Returns the full path |
length() |
long | Returns file size in bytes |
delete() |
boolean | Deletes the file |
Example: Exploring File Properties
5 Creating Files and Directories
You can also create new files and folders using the File class:
The createNewFile() method can throw an IOException, which we must handle with try-catch. We'll learn more about exceptions in a later module!
6 Summary
- ✓ The File class represents a file or directory path (not the actual content).
- ✓ Absolute paths give the complete location from root (less portable).
- ✓ Relative paths are relative to your project folder (more portable).
- ✓ Always check if a file exists() before trying to read it.
- ✓ File class provides methods to explore file properties and create files/folders.
The student asked, "Now I can find and check files, but how do I actually read what's inside them?"
The teacher smiled, "That's exactly what we'll learn in the next lesson - using Scanner to read from files!"