The File Class

Opening Files and Understanding Paths

Module 3 • Lesson 2 of 5

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."

What is the File Class?

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.

// Import the File class import java.io.File; // Create a File object pointing to "data.txt" File myFile = new File("data.txt");
Important to Understand

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:

📂 Absolute Path

Complete location from the root of the file system.

// Windows File f = new File("C:/Users/Student/data.txt"); // Linux/Mac File f = new File("/home/student/data.txt");
📁 Relative Path

Location relative to your project folder.

// Same folder as code File f = new File("data.txt"); // In subfolder "resources" File f = new File("resources/data.txt");
Project Folder Structure Example
MyProject/ ├── src/ │ └── Main.java ← Your code runs here ├── resources/ │ └── data.txt ← File("resources/data.txt") └── notes.txt ← File("notes.txt")
Problem with Absolute Paths

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!

Advantage of Relative Paths

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:

File myFile = new File("data.txt"); if (myFile.exists()) { System.out.println("File found!"); } else { System.out.println("File not found. Please check the path!"); }

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

import java.io.File; public class FileExplorer { public static void main(String[] args) { File myFile = new File("data.txt"); System.out.println("File name: " + myFile.getName()); System.out.println("Exists: " + myFile.exists()); System.out.println("Full path: " + myFile.getAbsolutePath()); System.out.println("Is file: " + myFile.isFile()); System.out.println("Is directory: " + myFile.isDirectory()); System.out.println("Can read: " + myFile.canRead()); System.out.println("Size (bytes): " + myFile.length()); } }
Sample Output (if file exists)
File name: data.txt Exists: true Full path: C:\Users\Student\MyProject\data.txt Is file: true Is directory: false Can read: true Size (bytes): 156

5 Creating Files and Directories

You can also create new files and folders using the File class:

import java.io.File; import java.io.IOException; public class CreateFiles { public static void main(String[] args) { // Create a new file File newFile = new File("newfile.txt"); try { if (newFile.createNewFile()) { System.out.println("File created!"); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("Error creating file."); } // Create a new directory File newDir = new File("myFolder"); if (newDir.mkdir()) { System.out.println("Directory created!"); } } }
Note About Exceptions

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

Key Takeaways
  • 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!"