The File Class
The java.io.File class is an abstract representation of file and directory pathnames. It does not allow you to read or write the actual contents of a file. Instead, it is used to interact with the file system—navigating directories, checking permissions, creating/deleting files, and querying metadata.
Creating a File Object
A File object is created by passing a pathname string (either relative or absolute) to its constructor.
// Using an absolute path
File absoluteFile = new File("/Users/username/documents/example.txt");
// Using a relative path (relative to the project's root directory)
File relativeFile = new File("src/resources/config.properties");
[!NOTE] Creating a
Fileobject does not create a physical file on the disk. It only creates an in-memory representation of the path.
Core Methods
The File class provides a wide range of methods to inspect and manipulate files and folders.
1. Verification and Attributes
exists(): Returnstrueif the file or directory physically exists.isFile(): Returnstrueif the path denotes a normal file (not a directory).isDirectory(): Returnstrueif the path denotes a directory.length(): Returns the size of the file in bytes (returns0for directories or if the file doesn't exist).canRead()/canWrite()/canExecute(): Checks file permissions.
2. File and Directory Creation
createNewFile(): Creates a new, empty file. Returnstrueif the file was successfully created, andfalseif it already exists. Throws anIOException.mkdir(): Creates the directory named by this abstract pathname. Returnstrueon success.mkdirs(): Creates the directory, including any necessary but non-existent parent directories.
3. File Deletion and Renaming
delete(): Deletes the file or directory. Note that a directory must be empty to be deleted.renameTo(File dest): Renames or moves the file to the destination path.
4. Navigation and Listing
getName(): Returns the name of the file or directory (the last element of the path).getAbsolutePath(): Returns the absolute path string.getParent(): Returns the parent directory path string, ornullif none.list(): Returns an array of strings naming the files and directories in the directory.listFiles(): Returns an array ofFileobjects representing the files and directories.
Practical Code Example
Here is a complete Java program demonstrating how to create a directory, create a file inside it, read its metadata, list the directory contents, and clean up.
import java.io.File;
import java.io.IOException;
public class FileOperationsDemo {
public static void main(String[] args) {
// 1. Define a directory and file path
File demoDir = new File("demo_directory");
File demoFile = new File(demoDir, "sample.txt");
try {
// 2. Create the directory if it doesn't exist
if (!demoDir.exists()) {
boolean dirCreated = demoDir.mkdir();
System.out.println("Directory created: " + dirCreated);
}
// 3. Create the file inside the directory
if (!demoFile.exists()) {
boolean fileCreated = demoFile.createNewFile();
System.out.println("File created: " + fileCreated);
}
// 4. Retrieve and display metadata
System.out.println("\n--- File Metadata ---");
System.out.println("File Name: " + demoFile.getName());
System.out.println("Absolute Path: " + demoFile.getAbsolutePath());
System.out.println("Is File? " + demoFile.isFile());
System.out.println("Is Directory? " + demoFile.isDirectory());
System.out.println("Size (Bytes): " + demoFile.length());
System.out.println("Writable? " + demoFile.canWrite());
// 5. List files in the directory
System.out.println("\n--- Listing Directory Contents ---");
File[] filesList = demoDir.listFiles();
if (filesList != null) {
for (File file : filesList) {
System.out.println("Found: " + file.getName() + " (" + file.length() + " bytes)");
}
}
// 6. Clean up (delete file first, then directory)
boolean fileDeleted = demoFile.delete();
boolean dirDeleted = demoDir.delete();
System.out.println("\n--- Clean Up ---");
System.out.println("File deleted: " + fileDeleted);
System.out.println("Directory deleted: " + dirDeleted);
} catch (IOException e) {
System.err.println("An error occurred during file operations: " + e.getMessage());
e.printStackTrace();
}
}
}
[!WARNING] The
delete()method deletes the file immediately without sending it to a recycle bin/trash. Use it with caution. Furthermore,delete()will fail on a directory if it contains any files or subdirectories.